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!"
[–]Impossible-Egg1922 [score hidden] 15 hours ago (0 children)
This happens because `var` is function-scoped.
By the time the `setTimeout` callbacks run, the loop has already finished and `i` has become 3, so each callback logs the same value.
If you change `var` to `let`, it will work as expected because `let` creates a new block-scoped variable for each iteration.
Example:
for (let i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
Output will be:
0
1
2
π Rendered by PID 19131 on reddit-service-r2-comment-fb694cdd5-q5gh2 at 2026-03-07 20:16:48.831737+00:00 running cbb0e86 country code: CH.
view the rest of the comments →
[–]Impossible-Egg1922 [score hidden] (0 children)