const and let

The two modern ways to declare a variable binding — const cannot be reassigned, let can.

                const name = value; / let name = value;
              

Purpose

const and let declare block-scoped variable bindings. const cannot be reassigned after its initial value is set; let can. Both replaced the older var, which has function scope instead of block scope and permits several mistakes const/let catch as errors.

Syntax

const taxRate = 0.08;
let total = 0;

total = total + 19.99; // fine — let allows reassignment
taxRate = 0.09; // TypeError: Assignment to constant variable.

Behavior notes

  • const must be initialized at declaration (const x; is a SyntaxError); let may be declared without an initial value, starting as undefined.
  • const prevents reassigning the binding, not mutating what it points to — const arr = [1]; arr.push(2); is legal, because arr itself is never reassigned. Only primitives are truly immutable this way; object contents can still change under a const binding.
  • Both are block-scoped: a binding declared inside { } (an if, a loop, a bare block) doesn’t exist outside it, unlike var.
  • Both are subject to the “temporal dead zone” — referencing the name before its declaration line runs throws a ReferenceError, rather than silently returning undefined the way var does.

Common mistakes

  • Using let everywhere out of habit. Defaulting to const and reaching for let only when reassignment is genuinely needed makes it easier for a reader to spot which values actually change.
  • Assuming const makes an array or object immutable — it only locks the binding, not the contents. Use Object.freeze() if true immutability is required.

Runtime notes

Part of ECMAScript since ES2015; identical behavior in every current browser and Node version.

Taught in these lessons

Related reference