Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Statements and Declarations

The const statement

Reference for the JavaScript const declaration: block scope, required initializer, why objects stay mutable, Object.freeze and use in loops.

The const declaration creates a block-scoped binding that cannot be reassigned. It must be given a value at the point of declaration. Apart from that, it behaves like let: same block scope, same temporal dead zone, no redeclaration in the same scope.

The key point is that const protects the binding, not the value. If the value is an object or array, you cannot point the name at something else, but you can still change what is inside it.

JavaScript
const maxItems = 10;
const user = { name: "Ada" };

Try it

JS A binding, not a frozen value

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS const in loops and destructuring

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
const name1 = value1;
const name1 = value1, name2 = value2;
const { a, b } = object;
const [first, second] = list;
Part Description
name A valid identifier or destructuring pattern.
value Required. Any expression.

Exceptions: a SyntaxError for a missing initializer (const x;) or a duplicate name in the same scope; a TypeError when you assign to the binding later; a ReferenceError when you read it before the declaration runs.

Usage notes

  • Immutable binding, mutable value. const list = []; list.push(1) is fine. To prevent changes to an object use Object.freeze() (shallow) or design the data as immutable.
  • Default choice. Declare with const unless you know you must reassign. This makes it obvious which values never change.
  • Naming. Many teams use UPPER_CASE only for true constants known at the top of a module (const MAX_RETRIES = 3), and ordinary camelCase for local const values computed at run time.
  • Loops. for (const x of items) and for (const k in obj) are fine because each iteration gets a new binding. A three-part for with a counter needs let.
  • Block scope and TDZ work exactly like let; closures capture the binding.
  • Functions. const add = (a, b) => a + b; makes a function that cannot be replaced by accident, but unlike a function declaration it is not hoisted for use.
  • Not a compile-time constant. The value can come from a function call or user input; const only forbids reassigning.

Browser support

Supported in every current browser and Node.js; part of the language since ES2015.