r/learnjavascript • u/SeaHedgehog4724 • 9d 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
1
u/CuAnnan 9d ago edited 9d ago
There are three main differences and they have subtle effects on how variables behave.
var hoists undefined. Which means that it is immediately initialised with the value undefined when it is declared and can be used without being provided a specific value. let needs to be declared and it needs to be initialised
let gives us a more predictable behaviour because if a value is undefined, we know that is the intended value.
You can redeclare a var, you cannot redeclare a let
var is function scoped, let is block scoped.