How to declare a constant in JavaScript?

Question:

How can I declare a constant in JavaScript? I'm looking for the equivalent (at least semantically) of

const int NUMERO_MAGICO=3;

in C .

Answer:

Use the const . Documentation in the MDN of the const .

Syntax

const name1 = value1 [, name2 = value2 [, name3 = value3 [, … [, nameN = valueN]]]];

Example

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

If you have a supported browser, you can try it out. Even if you try to change a variable defined with const , if you try to use it again it will keep the previous value

Compatibility

It is supported by newer versions of Engine Gecko (Firefox and the like), V8 (Chrome), and also Internet Explorer 11. Safari 5.1.7 and Opera 12 accept const , but allow the value to be changed later.

Edited: I tested now with NodeJS v0.10.20, which uses V8, and it worked like the documentation on MDN.

Use const Javascript in 2014?

If you want to write an application for a large audience, it's not worth using. Now if it's NodeJS or a small audience, I think you can give it a go.

Scroll to Top