liveBook · Manning

Const qualifier

As explained in Secrets of the JavaScript Ninja, Second Edition

A JavaScript binding declared with const that must be initialized at declaration and cannot be reassigned, although an object or array it references can still be modified.

When a value should keep its name and identity, const prevents accidental reassignment. Declare it with an initial value; later assignment of a new value throws an exception. Use meaningful names such as MAX_RONIN_COUNT instead of unexplained numeric literals. section 5.5.1 section 5.5

Keep the key distinction in mind:

  • const protects the binding from reassignment; it does not freeze an object or array it refers to. Properties can be added to an object, and an array can be changed with push. section 5.5.1
  • const is block-scoped, like let. Variables declared with either keyword belong to their closest environment, while var ignores blocks. section 5.5.2
try{
  firstConst = "ninja";
  fail("Shouldn't be here");
} catch(e){
  pass("An exception has occurred");
}

See the reassignment attempt that triggers an exception. section 5.5.1

secondConst.weapon = "wakizashi";
assert(secondConst.weapon === "wakizashi",
       "We can add new properties");

See an object referenced by const gain a property without reassignment. section 5.5.1

const thirdConst = [];
assert(thirdConst.length === 0, "No items in our array");

thirdConst.push("Yoshi");

assert(thirdConst.length === 1, "The array has changed");

See an array referenced by const change when an item is pushed. section 5.5.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains initialization, reassignment errors, mutable object contents, and block scope while contrasting var and let.
Examples
Demonstrates reassignment failure with a string, object property addition, array mutation, and scoped loop variables.
What you can do after
Apply const to prevent binding reassignment and give fixed values meaningful names.
How it connects
Connects const with let, var, lexical environments, block scope, and variable mutability.

Also explained in

Compare how 7 books explain const qualifier →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.