ES6+ (Modern JavaScript) · Foundations

let and const

Before ES6 there was only var, and it caused real bugs. let and const fix them. Rule of thumb: use const, switch to let only when the value must change, and never use var.

Beginner 5 min Lesson 2 of 23 Runnable examples
0/23 in ES6+
On this page · 5 min · Beginner

Learning objectives#

  • Explain block scope vs function scope
  • Choose between const and let
  • Understand that const prevents re-assignment, not mutation
  • Explain the temporal dead zone
  • Fix the var loop-closure bug

Explanation#

var is function-scoped: declared inside an if or for block, it leaks out to the whole function. let and const are block-scoped: they live only inside the nearest { }.

const means the variable cannot be re-assigned. But if it holds an object or array, the contents can still change: const cart = []; cart.push(x) is fine; cart = [] is an error.

let and const are hoisted but not initialised. Using them before their line throws a ReferenceError — this window is called the temporal dead zone (TDZ). var silently gives undefined instead.

In loops, let creates a fresh variable for every iteration, so callbacks remember the right value. var shares one variable across all iterations.

Syntax#

JavaScript Illustrative
const PI = 3.14;   // cannot be re-assigned
let count = 0;     // can change
count++;

Code example: var vs let vs const#

JavaScriptvar vs let vs const Runnable
if (true) {
  var a = 'var leaks out';
  let b = 'let stays inside';
}
console.log(a);
console.log(typeof b);


const cart = ['pen'];
cart.push('book');          // mutation is allowed
console.log(cart);
// cart = [];               // TypeError: Assignment to constant variable


for (var i = 0; i < 3; i++) setTimeout(() => console.log('var:', i));
for (let j = 0; j < 3; j++) setTimeout(() => console.log('let:', j));
Expected output
var leaks out
undefined
[ 'pen', 'book' ]
var: 3
var: 3
var: 3
let: 0
let: 1
let: 2
Opens this example in the full playground

Step-by-step explanation#

  1. a was declared with var inside the if block but is visible outside it.
  2. b only exists inside the block, so typeof b outside is "undefined".
  3. const cart can be pushed to — the variable still points to the same array.
  4. All three var callbacks share one i, which is 3 by the time they run.
  5. Each let iteration gets its own j, so the callbacks print 0, 1, 2.

Real-world use case#

Modern linters (ESLint’s no-var and prefer-const rules) enforce const-first code in almost every professional codebase.

Common mistakes#

Thinking const makes objects frozen

const only locks the variable binding. Use Object.freeze() if you really need an unchangeable object.

Using a variable before its let/const line

console.log(x); let x = 1; throws ReferenceError (TDZ). Declare variables before using them.

Re-declaring with let

let x = 1; let x = 2; in the same scope is a SyntaxError. var allowed it, which hid bugs.

Best practices#

  • Default to const
  • Use let for counters and values that are re-assigned
  • Never use var in new code
  • Declare variables in the smallest scope that needs them

Remember this#

const by default, let when it changes, var never.

const = the label is glued to the box; you can still change what is in the box.

Braces { } are a fence for let and const — var jumps the fence.

Practice exercise#

Your task: Fix this so it logs 1, 2, 3 instead of 4, 4, 4: for (var n = 1; n <= 3; n++) setTimeout(() => console.log(n));

Need a hint?
Change one keyword.
Show solution
JavaScript Runnable
for (let n = 1; n <= 3; n++) setTimeout(() => console.log(n));
// 1 2 3
Opens this example in the full playground

Mini quiz#

let and const quizFind the error Question 1 of 3

Which line throws an error?

const user = { name: 'Asha' };
user.name = 'Ravi';   // line 2
user.age = 25;        // line 3
user = {};            // line 4
Score so far: 0/0

Want more? Practise all ES6+ MCQs · ES6+ interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.