Skip to content

Changing a const cart

JavaScript · Scope and hoisting

JavaScript#5 · 6 Dec 2026

Changing a const cart

const cart = ["chai"];
cart.push("samosa");
console.log(cart.length);
cart = [];
console.log(cart.length);

What does this print?

Show the answer without guessing

It prints: 2 TypeError

const fixes the variable binding, not the value inside it. You can still push to the array, so the length becomes 2. Pointing cart at a new array is a reassignment, and that throws a TypeError: Assignment to constant variable.

const stops reassignment, not mutation; use Object.freeze if the contents must not change.