var is function-scoped, while let and const are block-scoped. const also cannot be reassigned.
var:
- It is visible in the whole function. It ignores blocks like
ifandfor. - It is hoisted (registered before the code runs) and starts as
undefined. - You can declare it again in the same scope without an error.
- At the top level of a script, it becomes a property of the global object, like
window.x.
let and const:
- They are visible only inside their block
{ ... }. - They are hoisted too, but they stay uninitialized until their declaration line runs. This period is the temporal dead zone (TDZ). Reading them during the TDZ throws a
ReferenceError. - You cannot declare them again in the same scope.
const only:
- You cannot reassign it, and you must give it a value when you declare it.
- It does not make the value immutable. You can still change a
constobject or array, for examplelist.push(4).
A good default: use const, use let when you need to reassign, and do not use var.
varis function-scoped.letandconstare block-scoped.- Hoisted
varstarts asundefined.letandconstare in the temporal dead zone (TDZ) until their line runs. varcan be declared twice, and at the top level it creates a property on the global object.conststops reassignment, but the object or array inside can still change.
Read more
- The old var (https://javascript.info/var)javascript.info
- let (MDN) (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let)developer.mozilla.org