How to declare a constant in Javascript?

Asked

Viewed 9,017 times

27

How can I declare a constant in Javascript? I am looking for the equivalent (at least semantically) of

const int NUMERO_MAGICO=3;

in C.

  • there is also in some styleguides the simple standard: var NUMERO_MAGICO = 3; google uses the same.

4 answers

15

It is not possible to create a constant directly, but you can declare a function that always returns the same value:

function constante(valor) {
    return function() {
        return valor;
    }
}

var NUMERO_MAGICO = constante(3);

// uso:
var x = NUMERO_MAGICO();

This way, nothing can change the value after created. But is still possible reassign NUMERO_MAGICO for another value or constant:

var NUMERO_MAGICO = constante(42); // Funciona sem problemas

There is the proposal (in Ecmascript 6) to introduce the keyword const (as pointed out by @Emerson Rocha Luiz), but at the moment it is not standardized, nor supported by all browsers (also not sure about server-side Javascript).

Finally, there is the possibility of marking a property of an object as read-only:

var obj = {};
Object.defineProperty(obj, "NUMERO_MAGICO", {
    value: 3,
    writable: false
});

var x = obj.NUMERO_MAGICO;
obj.NUMERO_MAGICO = 42; // Não tem efeito
console.log(obj.NUMERO_MAGICO); // 3

However, in the same way as in the first example, one can still reassign obj. If you want to declare an object to store all its constants, you can make the whole object read-only through Object.freeze:

var constantes = { A: 10, B: 20, C:30 };
Object.freeze(constantes);

instead of declaring each property that way, one by one. Just be careful with the performance (as pointed out in the comments, it can be much worse than an unfrozen object, depending on the implementation).

Observing: regardless of the method chosen, it is good to remember that if its constant is a complex object, the reference to it may be immutable but it does not necessarily be:

var OBJETO_MAGICO = constante({ "foo":"bar" });
OBJETO_MAGICO().foo = "baz"; // Funciona sem problemas

For the question of "how to make a complex object immutable", see that related question.

  • 1

    I stopped and tested here with Nodejs installed on my machine and it worked. I personally do not use it, but maybe even use it. But I don’t remember if it makes any difference as far as performance improvement , although the constant purpose is really focused on be constant.

  • 1

    I tested it on ideone with Rhino, and is also supported. Same behavior - reallocation fails silently.

  • 1

    Other pertinent comment on the Object.freeze that only occurs with V8, including recent. For some cases it is much, but much slower. I was using it in Nodejs and I abandoned it when I saw that it got worse. Here in detail http://stackoverflow.com/questions/8435080/any-performance-benefitto-locking-down-javascript-objects

14


Use the const. Documentation on const MDN.

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 test it. Even if you try to change a variable set 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 have now tested with Nodejs v0.10.20, which uses V8, and worked like the documentation on MDN.

Use Javascript const in 2014?

If you want to write an application for a large audience, it is not worth using. Now whether it’s Nodejs or a reduced audience, I think you can give it a try.

  • 1

    I was going to talk about compatibility, but I’m glad you edited and quoted.

  • 1

    I confirm that const works in IE11 and that the value nay may be amended later.

  • 1

    jsfiddle for anyone who wants to test in their browser: http://jsfiddle.net/WpcQm/

  • 2

    Another trick is that the const Mozilla’s non-standard does not behave like const that should exist in ES6 (which will have block scope, such as with let).

3

Based on the possibility of properties of an object such as read-only of reply from @mgibsonbr, and considering the correct response of @Emerson Rocha Luiz, on the use of const, only not yet supported by most browsers. I created a more coherent and usual solution for the current usage scenario (of the browsers), which consists of the following (follow comments):

// ao invés de definir a propriedade read-only a um objeto qualquer,
// se define a propriedade read-only (suposta constante) ao objeto que as propriedades roots e globais são anexados.
Object.defineProperty(window, "NUMERO_MAGICO", {
  value: 3,
  writable: false
});

// assim pode-se utilizar o valor como um objeto global e constante
// sendo que a unica forma de redefini-lo ou exclui-lo é redefinindo o objeto window
var x = NUMERO_MAGICO;
NUMERO_MAGICO = 42; // Não tem efeito
document.body.innerHTML = NUMERO_MAGICO; // 3

Thus, being the closest way to obtain a behavior similar to a constant (with greater compatibility) in javascript.

Compatibility:

I tested in the following browsers (using this jsFiddle):

<table border="1" bordercolor="#ccc">
	<thead><tr><th>Navegador</th><th>Versão</th><th>Compativél</th></tr></thead>
	<tbody>
		<tr><td>IE</td><td>11</td><td>Sim</td></tr>
		<tr><td>Maxthon</td><td>4.4</td><td>Sim</td></tr>
		<tr><td>Chrome Canary</td><td>43.0</td><td>Sim</td></tr>
		<tr><td>Opera beta (Next)</td><td>29.0</td><td>Sim</td></tr>
		<tr><td>Firefox</td><td>36.0</td><td>Sim</td></tr>
		<tr><td>Opera</td><td>28.0</td><td>Sim</td></tr>
		<tr><td>Safari</td><td>5.1.7</td><td>Sim</td></tr>
	</tbody>
</table>

(Test on your browsers and edit this listing, to really verify the compatibility of that solution);

2

No variable is always constant in javascript, but you can do the following:

var NUMERO_MAGICO = 3;

About the int javascript automatically assigns typing according to the value received in the variable.

  • 3

    well that could at least change Nothing is ever constant in his reply

Browser other questions tagged

You are not signed in. Login or sign up in order to post.