Salvador Dali Salvador Dali - 1 month ago 6
Javascript Question

Why can I change value of a constant in javascript

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

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'}

and this

const y = [];

y.push('foo');

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

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