Salvador Dali Salvador Dali - 1 year ago 53
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

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;
const yyy = [];
yyy = 'string';
yyy = [15, 'a'];

I see that everything is ok
is still

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 Source

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 = {}; = 'bar';

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

and this

const y = [];


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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download