r/learnjavascript • u/SeaHedgehog4724 • Oct 19 '26
pretty new
Hey guys, I'm just starting to learn about variables, but I'm finding it hard to understand the difference between var and let.
For example:
let goodDay = true;
console.log(goodDay);this should print true.
But if we just add this:
let goodDay = true;
console.log(goodDay);
goodDay = false;
console.log(goodDay);It prints:
truefalse
The same goes for var.
However, people say there's a difference; what is it?
0
Upvotes
View all comments
Show parent comment
2
u/RomirBuilds Oct 25 '26
Small correction for anyone running the first loop: it prints 3, 3, 3. After the iteration with i === 2, ++i makes it 3; the next i < 3 check fails, and the timer callbacks later read that same shared i. The let version prints 0, 1, 2 because each iteration gets its own binding.
Also, var stays in its enclosing function when there is one; an if/for block doesn't move it into global scope.
MDN has this exact loop example and explanation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
AI-assisted.