JS: const Declaration

By Xah Lee. Date: . Last updated: .

New in ES2015.

const is for declaring constants. It's similar to let, except you can't change its value once set.

[see JS: let Declaration]

// variable declared with const cannot be changed
const x = 3;
x = 4; // TypeError: Assignment to constant variable.

const Must Have a Value When Declared

const must have a value when declared.

// const must have a value
const x; // SyntaxError: Missing initializer in const declaration
x = 3;

Prevent Add/Delete/Change Object Propecties

If a object value is declared const, you can still add/delete/change properties of the object.

// if object is declared constant, the object properties can still be modified
const ob = {};
ob.p = 3;
console.log(ob); // { p: 3 }

Note, you can prevent add/delete/change properties by using

[see JS: Prevent Adding Property]

No Name Hoisting

The const doesn't have name hoisting as var does. That means, you can't use the name before its const declaration.

[see JS: var Declaration Order]

JS Variable

  1. Value Types
  2. let
  3. const
  4. var
  5. var Order
  6. var Scope
  7. Global Variable
  8. Destructuring Assignment
Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog