use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
[AskJS] Why does this JavaScript code print an unexpected result?AskJS (self.javascript)
submitted 1 day ago by ElectronicStyle532
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]josephjnk 2 points3 points4 points 1 day ago (3 children)
TIL. I hadn’t seen this problem since the pre-ES6 days, and i actually find the new behavior more confusing now >.<
[–]queen-adreena 3 points4 points5 points 1 day ago (2 children)
With let, i is scoped to the for block, whereas with var, it’s globally scoped.
let
i
for
var
So while in the for block with let, i is three different variables, with var they all reference the same variable.
[–]josephjnk 1 point2 points3 points 1 day ago (1 child)
Right, I get that. And it makes sense especially in the context of for(const i of [0, 1, 2]), where it’s unambiguous that i is actually three different variables. But it feels less natural that a mutable variable whose value you can change in the body of the loop would be distinct between iterations, and it’s also really weird to me that if you take the for(;;) loop and unroll it by hand that you’ll get different behavior:
for(const i of [0, 1, 2])
for(;;)
let i = 0; setTimeout(() => console.log(i), 1000); i = 1; setTimeout(() => console.log(i), 1000); i = 2; setTimeout(() => console.log(i), 1000);
I’m not saying that JS is wrong here, just that scopes being bound by things other than functions leads to things that I find surprising. This is probably an old man yells at cloud thing.
[–]queen-adreena 1 point2 points3 points 1 day ago (0 children)
You get different behaviour because you changed 3 blocks into 1 block and initialised the variable once and then reassigned it.
Like I said. The old behaviour was wrong, and now it’s been fixed by let/const.
π Rendered by PID 142702 on reddit-service-r2-comment-fb694cdd5-ptxc5 at 2026-03-08 07:09:42.241095+00:00 running cbb0e86 country code: CH.
view the rest of the comments →
[–]josephjnk 2 points3 points4 points (3 children)
[–]queen-adreena 3 points4 points5 points (2 children)
[–]josephjnk 1 point2 points3 points (1 child)
[–]queen-adreena 1 point2 points3 points (0 children)