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.
const maxItems = 10; const user = { name: "Ada" };
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
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 useObject.freeze()(shallow) or design the data as immutable. - Default choice. Declare with
constunless you know you must reassign. This makes it obvious which values never change. - Naming. Many teams use
UPPER_CASEonly for true constants known at the top of a module (const MAX_RETRIES = 3), and ordinary camelCase for localconstvalues computed at run time. - Loops.
for (const x of items)andfor (const k in obj)are fine because each iteration gets a new binding. A three-partforwith a counter needslet. - 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 afunctiondeclaration it is not hoisted for use. - Not a compile-time constant. The value can come from a function call or user input;
constonly forbids reassigning.
Browser support
Supported in every current browser and Node.js; part of the language since ES2015.
Related
let,var,Object.freeze()- Lessons: Variables, Scope, Copying objects