Card 1 of 10 · Basics
var vs let vs const: what is the difference?
Say this first
var is function-scoped and hoisted as undefined. let and const are block-scoped and cannot be used before their line. const cannot be reassigned.
Picture it
| var | let | const | |
|---|---|---|---|
| Scope | Function | Block | Block |
| Before its line | undefined | ReferenceError (temporal dead zone) | ReferenceError |
| Reassign | Yes | Yes | No (but an object's contents can change) |
| Use today | Avoid | When it changes | Default choice |
Try it
What does console.log(b); var b = 1; print?
Common trap
Saying const makes a value immutable. It only stops reassigning the variable; an object or array can still be changed.
Say it like this
I default to const, use let when a value changes, and avoid var because of its function scope and hoisting.