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
constmust be initialized at declaration (const x;is aSyntaxError);letmay be declared without an initial value, starting asundefined.constprevents reassigning the binding, not mutating what it points to —const arr = [1]; arr.push(2);is legal, becausearritself is never reassigned. Only primitives are truly immutable this way; object contents can still change under aconstbinding.- Both are block-scoped: a binding declared inside
{ }(anif, a loop, a bare block) doesn’t exist outside it, unlikevar. - Both are subject to the “temporal dead zone” — referencing the name before its declaration line
runs throws a
ReferenceError, rather than silently returningundefinedthe wayvardoes.
Common mistakes
- Using
leteverywhere out of habit. Defaulting toconstand reaching forletonly when reassignment is genuinely needed makes it easier for a reader to spot which values actually change. - Assuming
constmakes an array or object immutable — it only locks the binding, not the contents. UseObject.freeze()if true immutability is required.
Runtime notes
Part of ECMAScript since ES2015; identical behavior in every current browser and Node version.