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 trialnfs
35,526 PointsDo 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
Treehouse TeacherThe 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
nfs
35,526 PointsYes, 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.
nfs
35,526 PointsThank you, Dave McFarland. Later I did learn more about closures, global scope, lexical scope etc. Thanks a lot to all the teachers of Treehouse.
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 PointsAakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 PointsCan 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?'
nfs
35,526 Pointsnfs
35,526 PointsAakash Srivastav, yes. Check this one out for more info.
Joseph Lander
Full Stack JavaScript Techdegree Graduate 27,765 PointsJoseph Lander
Full Stack JavaScript Techdegree Graduate 27,765 PointsI 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
andconst
fix a bug/quirk in the JS language thatvar
is hoisted out of a block as opposed to them having special powers.-- just highlighting