Back

const

const

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, solely that the variable identifier can not be reassigned.

Syntax

const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]];
nameN
Constant name. It can be any legal identifier.
valueN
Value of the constant. It can be any legal expression.

Description

This declaration creates a constant that can be global or local to the function in which it is declared. Constants are block-scoped. The value of a constant cannot change through re-assignment, and a constant cannot be re-declared. An initializer for a constant is required. A constant cannot share its name with a function or a variable in the same scope.

Examples

The following example demonstrates how constants behave. Try this in your browser console.

// NOTE: Constants can be declared with uppercase or lowercase, but just by convention, we are using uppercase
// define my_fav as a constant and give it the value 7
const MY_FAV = 7;

// this will fail silently in Firefox and Chrome (but does not fail in Safari)
MY_FAV = 20;

// will print 7
console.log("my favorite number is: " + MY_FAV);

// trying to redeclare a constant throws an error 
const MY_FAV = 20;

// the name MY_FAV is reserved for constant above, so this will also fail
var MY_FAV = 20; 

// MY_FAV is still 7
console.log("my favorite number is " + MY_FAV);

// Assigning to A const variable is a syntax error
const A = 1; A = 2;

// const requires an initializer
const FOO; // SyntaxError: missing = in const declaration

// const also works on objects
const MY_OBJECT = {"key": "value"};

// Overwriting the object fails as above (in Firefox and Chrome but not in Safari)
MY_OBJECT = {"OTHER_KEY": "value"};

// However, object attributes are not protected,
// so the following statement is executed without problems
MY_OBJECT.key = "otherValue";

Compatibility notes

In earlier versions of Firefox & Chrome and as of Safari 5.1.7 and Opera 12.00, if you define a variable with const, you can still change its value later. It is not supported in Internet Explorer 6-10, but is included in Internet Explorer 11.

Firefox-specific notes

The const declaration has been implemented in Firefox long before const appeared in the ECMAScript 6 specification. For const ES6 compliance see and .


  Created by Mozilla Contributors, license: CC-BY-SA 2.5