Saturday, May 11, 2024
119
rated 0 times [  123] [ 4]  / answers: 1 / hits: 144378  / 10 Years ago, fri, may 2, 2014, 12:00:00

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;.


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


More From » ecmascript-6

 Answers
15

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

[#71201] Wednesday, April 30, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hailie

Total Points: 25
Total Questions: 112
Total Answers: 111

Location: Belize
Member since Tue, Dec 8, 2020
4 Years ago
hailie questions
;