JavaScript const

The const keyword was introduced in ES6 (2015). Use const when the variable value should not be reassigned. It must be initialised at declaration.

const Cannot Be Reassigned

Immutable Binding
const PI = 3.14159;
console.log(PI);

// PI = 3;   // TypeError: Assignment to constant variable

const Must Be Initialised

Initialisation at Declaration
const MAX = 100;   // OK

// const LIMIT;    // SyntaxError: Missing initializer in const declaration

const Objects Are Mutable

const prevents reassigning the variable, but it does NOT make the object immutable. Properties can still be changed.

const Object — Properties Can Change
const person = { name: "Alice", age: 30 };

person.age  = 31;           // OK — mutating a property
person.city = "Paris";      // OK — adding a property
console.log(person);

// person = {};  // TypeError — reassigning const is not allowed

const Arrays Are Mutable

const Array — Elements Can Change
const colors = ["red", "green", "blue"];

colors.push("yellow");    // OK — mutating array
colors[0] = "white";      // OK — changing element
console.log(colors);

// colors = [];  // TypeError — reassigning const is not allowed

const vs let vs var

Featureconstletvar
ScopeBlockBlockFunction
Reassign✗ No✓ Yes✓ Yes
Redeclare✗ No✗ No✓ Yes
Must initialise✓ Yes✗ No✗ No
HoistedTDZTDZ✓ (undefined)
📝 Note: Best practice: use const by default. Switch to let only when you know the value needs to change. Never use var in modern code.
Exercise:
Can you change properties of a const object?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.