Why can I change value of a constant in javascript

Salvador Dali picture Salvador Dali · May 2, 2014 · Viewed 62.8k times · Source

I know that ES6 is not standardized yet, but a lot of browsers currently support const keyword in JS.

In spec, it is written that:

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.

and when I do something like this:

const xxx = 6;
xxx = 999;
xxx++;
const yyy = [];
yyy = 'string';
yyy = [15, 'a'];

I see that everything is ok xxx is still 6 and yyy is [].

But if I do yyy.push(6); yyy.push(1);, my constant array has been changed. Right now it is [6, 1] and by the way I still can not change it with yyy = 1;.

I this a bug, or am I missing something? I tried it in the latest chrome and FF29

Answer

adeneo picture adeneo · May 2, 2014

The documentation states:

...constant cannot change through re-assignment
...constant cannot be re-declared

When you're adding to an array or object you're not re-assigning or re-declaring the constant, it's already declared and assigned, you're just adding to the "list" that the constant points to.

So this works fine:

const x = {};

x.foo = 'bar';

console.log(x); // {foo : 'bar'}

x.foo = 'bar2';

console.log(x); // {foo : 'bar2'}  

and this:

const y = [];

y.push('foo');

console.log(y); // ['foo']

y.unshift("foo2");

console.log(y); // ['foo2', 'foo']

y.pop();

console.log(y); // ['foo2']

but neither of these:

const x = {};
x = {foo: 'bar'}; // error - re-assigning

const y = ['foo'];
const y = ['bar']; // error - re-declaring

const foo = 'bar'; 
foo = 'bar2';       // error - can not re-assign
var foo = 'bar3';   // error - already declared
function foo() {};  // error - already declared