Skip to content
javascript questions

JavaScript · 1 of 10junior~1 min

What is the difference between var, let, and const?

#core#scope

var vs let vs const

Scope

js
function example() { var a = 1; // function-scoped let b = 2; // block-scoped const c = 3; // block-scoped if (true) { var a = 10; // same variable - overwrites! let b = 20; // new variable - only inside this block console.log(b); // 20 } console.log(a); // 10 - was overwritten console.log(b); // 2 - untouched }

Hoisting

js
console.log(a); // undefined - hoisted but not initialized console.log(b); // ReferenceError - temporal dead zone var a = 1; let b = 2;

Reassignment

js
var x = 1; x = 2; // ok let y = 1; y = 2; // ok const z = 1; z = 2; // Error - cannot reassign // const with objects - reference is locked, contents are not const user = { name: 'Alice' }; user.name = 'Bob'; // ok user = {}; // Error

Comparison

varletconst
ScopeFunctionBlockBlock
HoistingYes (undefined)TDZTDZ
ReassignYesYesNo
Re-declareYesNoNo

Rule: use const by default, let when you need to reassign, never use var.

updated

did you know it?

related questions