Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Uses for Closures

Do we need closures anymore?

Now that we have block-level scoping with let and const, do we need to use closures anymore?

3 Answers

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

The best example of how let helps with scope issues is the for loop shown in this video. let by itself doesn't avoid problems with global scope. For example in this code

let i = 1;
function count() {
  return i++;
}
count();
count();
console.log(i); // i is now 3 in the global scope
Aakash Srivastav
seal-mask
.a{fill-rule:evenodd;}techdegree
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 Points

Can we increment a local counter with 'let' without using the 'closure' ?
I mean , i don't want to use global variable and also don't want to use closure .
Is still its possible to achive the desired result?'

Aakash Srivastav, yes. Check this one out for more info.

I think this is an important point that let doesn't make it just work.

This example is highlighting that if you declare it in a globally accessible place, then it will be globally accessible. If you declare it in a block, it will only be accessible in that block. This is the way I believe we would naturally expect it to have worked when using var, but it doesn't.

It feels as if let and const fix a bug/quirk in the JS language that var is hoisted out of a block as opposed to them having special powers.

-- just highlighting

// global area
let i = 1;

function count() {
// block area
  return i++;
}

Yes, we do. Later I was taking React courses and Guil was talking about closures. He pointed out that closures are everywhere in React. So better familiarize yourself.

But in case anyone's wondering, let and const are very effective in eliminating the use of closures in a lot of cases.

:smile:

Thank you, Dave McFarland. Later I did learn more about closures, global scope, lexical scope etc. Thanks a lot to all the teachers of Treehouse.