Skip to the content

Lesson 51 of 296

var vs let vs const

What you will learn

  • Every difference between var, let and const
  • Why var causes bugs
  • What to use in modern code
On this page

The full comparison

varletconst
ScopeFunctionBlockBlock
Can be reassignedYesYesNo
Can be declared again in the same scopeYesNoNo
HoistedYes, and set to undefinedYes, but not usable (TDZ)Yes, but not usable (TDZ)
Using it before its lineGives undefinedReferenceErrorReferenceError
Must have a value when createdNoNoYes
Top-level in a browser script creates a window propertyYesNoNo
Introduced1995ES6 (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);    0

With 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 replaced

With 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

  1. const by default.
  2. let when the variable must be reassigned.
  3. Never var in 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 let and const into var.

Common mistakes

  • Using var out of habit.
  • Thinking const makes objects unchangeable (Lesson 48).
  • Using let for 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

WordMeaning
varThe old way to declare variables; function-scoped
letBlock-scoped, can be reassigned
constBlock-scoped, cannot be reassigned
RedeclareDeclare the same name again in the same scope
LinterA tool that warns about risky code patterns

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.