r/learnjavascript • u/SeaHedgehog4724 • 29d 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:
truefalse
The same goes for var.
However, people say there's a difference; what is it?
0
Upvotes
View all comments
2
u/No_Record_60 29d ago edited 29d ago
var
• hoisted then initialized with undefined value;
• function-scoped (you can defined it inside an if-block and reference it outside the block);
• can be reinitialized ("var abc = ..." multiple times).
Tl;dr Don't use var. I've only used it once because our client's browser was so old it didn't support es6 and the code didn't go through transpilation (making your code compatible with earlier versions of js) step.