JavaScript: 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 JavaScript: let Declaration

const must have a value when declared.

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

If a object value is declared const, you can still 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 }

const must have a value when declared.

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

Reference

ECMAScript 2015 §ECMAScript Language: Statements and Declarations#sec-let-and-const-declarations

JavaScript Variable Topic

  1. JavaScript: Variable
  2. JavaScript: Variable/Function Declaration Order, Name Hoisting
  3. JavaScript Variable Scope: Function Level vs Block Level
  4. JavaScript: let Declaration
  5. JavaScript: const Declaration
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.