Can you guess what this prints out?
for (var i=0; i<3; i++) {
setTimeout(() => console.log(i), 2000)
}
Enter fullscreen mode
...
For further actions, you may consider blocking this person and/or reporting abuse
As far as I can tell (tested in node, chrome and safari), your first example prints 3 three times, not 2. This is because the variable is set to three, checked that it doesn't fulfill
i < 3
and then exits the for loop and retains the value 3Gosh, of course. Thanks for the note. Fixed!
Great post, by the way
Thank you so much!
Nice article, especially for the pointer to how closures are used and handled in other languages. For me it was the first time to hear about
nonlocal
in python although I claim I've known python for quite a long time.Thanks Mohammed :) I appreciate you telling me what was most helpful. I’ve heard this from a couple other folks who know python too.
Or you could simplify everything using modern javascript and not using old and deprecated var but instead let...?
It seems like the simplest solution, I didn't quite understand why you didn't talk about it.
Hi Ricardo! It’s simple really. What I was interested in was creating a toy problem that would serve for learning purposes, that would help clarify how closures (and scope) work. If you think of a different example of closures that would similarly clarify the points above, I’m happy to hear them.
You should test your example :
for (let i=0; i<3; i++) {
setTimeout(() => console.log(i), 2000)
}
It prints out 0,1,2 as expected. Because you used let to declare i. Can you guess why ?
I also put the ++ in the wrong spot according to my notes. Fixed that as well!
Please also check your factory example, factory(4)(2) returns an error. Your namespacer function also returns undefined for namespacer.public1(); and
namespacer.public2();
Fixed! Thanks again :D
Lol, my bad. I have var written in my notes, but typed let here when I wrote the blog post! Thanks for pointing this out!
This is brillliant! Very well written, I may have to refer back to this. Often. Thanks for it!
Thank you Toby. That makes me happy. I’m glad it’s useful!
This does seem like a good reference to have on hand. Thank you. The article is well written.
Thanks Sonny. Happy to hear it’s useful.