I'm wondering what is the difference between let
and const
in ES6. Both of them are block scoped, as the example in the following code:
const PI = 3.14;
console.log(PI);
PI = 3;
console.log(PI);
const PI = 4;
console.log(PI);
var PI = 5;
console.log(PI);
In ES5 the output will be:
3.14
3.14
3.14
3.14
But in ES6 it will be:
3.14
3
4
5
I'm wondering why ES6 allows the change of const
value, the question is why should we use 'const' now? we can use 'let' instead?
Note: jsbin can be used for testing, choose JavaScript to run ES5 code and Traceur to run it with ES6 capabilities.
What you're seeing is just an implementation mistake. According to the ES6 spec wiki on const
, const
is:
A initialize-once, read-only thereafter binding form is useful and has precedent in existing implementations, in the form of const declarations.
It's meant to be read-only, just like it currently is. The ES6 implementation of const
in Traceur and Continuum are buggy (they probably just overlooked it)
Here's a Github issue regarding Traceur not implementing const