Lesson 51 of 296
var vs let vs const
What you will learn
- Every difference between
var,letandconst - Why
varcauses bugs - What to use in modern code
On this page
The full comparison
var | let | const | |
|---|---|---|---|
| Scope | Function | Block | Block |
| Can be reassigned | Yes | Yes | No |
| Can be declared again in the same scope | Yes | No | No |
| Hoisted | Yes, and set to undefined | Yes, but not usable (TDZ) | Yes, but not usable (TDZ) |
| Using it before its line | Gives undefined | ReferenceError | ReferenceError |
| Must have a value when created | No | No | Yes |
Top-level in a browser script creates a window property | Yes | No | No |
| Introduced | 1995 | ES6 (2015) | ES6 (2015) |
TDZ (the temporal dead zone) is explained in Lesson 52.
Problem 1: var ignores blocks
var total = 100;
if (true) {
var total = 0; meant as a new variable, but it is the SAME one
}
console.log(total); 0With let, the inner total would be a separate variable, and the outer one would stay 100.
Problem 2: var can be declared twice
var user = "Sam";
var user = "Ali"; no error, the first is silently replacedWith let or const, this is a SyntaxError, which catches the mistake immediately.
Problem 3: var can be used before it is declared
console.log(price); undefined (no error)
var price = 10;The code runs but gives a wrong value. With let, you get a clear error.
Problem 4: var in loops
for (var i = 0; i < 3; i++) { }
console.log(i); 3 (i leaks out of the loop)This also causes the famous setTimeout bug (Lesson 54).
What to use
constby default.letwhen the variable must be reassigned.- Never
varin new code.
Most linters (for example ESLint's no-var rule) enforce this.
Why you still need to know var
- Old codebases and tutorials use it.
- Interview questions about hoisting, scope and closures are often built around
var. - Some older code compiled for old browsers turns
letandconstintovar.
Common mistakes
- Using
varout of habit. - Thinking
constmakes objects unchangeable (Lesson 48). - Using
letfor everything, which hides which values really change.
How to say it in an interview
"var is function-scoped, can be redeclared, and is hoisted with the value undefined, so it can be read before its line without an error. let and const are block-scoped, cannot be redeclared, and are in the temporal dead zone until their declaration runs. const also cannot be reassigned and must be initialised. I use const by default, let when I need to reassign, and never var."
Key words
| Word | Meaning |
|---|---|
var | The old way to declare variables; function-scoped |
let | Block-scoped, can be reassigned |
const | Block-scoped, cannot be reassigned |
| Redeclare | Declare the same name again in the same scope |
| Linter | A tool that warns about risky code patterns |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.