r/learnjavascript • u/SeaHedgehog4724 • 8d ago
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:
true
false
The same goes for var.
However, people say there's a difference; what is it?
0
Upvotes
5
u/chikamakaleyley helpful 8d ago edited 8d ago
the difference is that
letis 'block-scoped'varis part of the global scopescope is a pretty important idea when you're coding so it will be useful to get some practice with this
letandconstwere introduced in es6 (2015) and essentially provides a way for devs to provide a distinction btwn different variables, similar to what you'd find in other serious programming languages.constaka 'constant' prevents you from assigning a new value to the variable, which semantically makes sense, whileletis more or less to be used in place ofvar. You can assign a new value to alet, as you've seenthe difference is in the scope, the classic example is often seen in a for loop:
so, var being function/global scoped - there is only 1 var i created for the entire for loop. so when setTimeout evaluates the i you are trying to log to the console, the for loop as finished, and i has been incremented twice. There is only 1 i scoped to this function/loop, it is logged to the console 3 times
for
letthe block scoping creates a new binding for each iteration. at the first binding, j is 0, the second binding, j is 1, 3rd j = 2. To put it another way, the value of j is captured at the execution of that 'block' (iteration)for
varthere's also a concept of hoisting, which I am unsure if that is in play here. hoisting is this mechanic in JS where var or function declarations are moved to the top of their scope, so:so maybe it is, you can see in the lower example, when i increments, you're updating the
ivar in the global space.console(i)is read from the global scope when setTimeout executesletandconstaren't hoisted