const

Summary

Declares a read-only, named constant.

Statement
Implemented in: JavaScript 1.5, NES 6.0 (Netscape extension, C engine only)

Syntax

const varname1 = value1 [, varname2 = value2 [, varname3 = value3 [, ... [, varnameN = valueN]]]];

Parameters

varnameN
Constant name. It can be any legal identifier.
valueN
Value of the constant. It can be any legal expression.

Description

Creates a constant that can be global or local to the function in which it is declared. Constants follow the same scope rules as variables.

The value of a constant cannot change through re-assignment, and a constant cannot be re-declared. Because of this, although it is possible to declare a constant without initializing it, it would be useless to do so.

A constant cannot share its name with a function or a variable in the same scope.

Browser compatibility

The current implementation of const is a Mozilla-specific extension and is not part of ECMAScript 5. It is supported in Firefox & Chrome (V8) and partially supported in Opera 9+ and Safari. It is not supported in Internet Explorer 6-9, or in the preview of Internet Explorer 10. The const keyword currently declares the constant in the function scope (like variables declared with var).

const is going to be defined by ECMAScript 6, but with different semantics. Similar to variables declared with the let statement, constants declared with const will be block-scoped.

Examples

The following example produces the output "a is 7."

const a = 7;
console.log("a is " + a + ".");

Tags (3)

Edit tags

Attachments (0)

 

Attach file