Ecmascript 6 Features 6: const
We have reached the 6th post in the ES6 features series! This series of posts has to be my longest yet. This week's post is a short one about a new keyword that has been added in ES6: const. If you know any C♯, then this keywrod may already be familiar to you. It's purpose is to define a variable (called a constant) that cannot be changed or redefined.
As with normal variables, constants are function scope. When defined outside a function, they become part of the global scope. Example:
> const max_value = 64;
undefined
> max_value
64
Since constants can't be changed, setting them to a different value has no effect (but doesn't throw an error - wait, what?):
> max_value = 128;
128
> max_value
64
Redefining a constant throws an error:
> max_value
64
> const max_value = 128
TypeError: Identifier 'max_value' has already been declared
And they can't be deleted either:
> delete max_value
false
> max_value
64
It seems that you can't define a constant as a property of an object though (makes sense - then it would be a property and not a variable I suppose, though having the the syntax work like that would make things so much more readable). For that, you'll have to use Object.defineProperty() with the writable: false option.
> settings = {};
{}
> const settings.seed = 47264;
SyntaxError: Unexpected token .
Other than that, they behave like normal variables. For example you can convert a constant number to a string as normal:
> max_value.toString(2)
'1000000'
>
Though curiously, mutators on constants work correctly and change the original variable (perhaps this is a bug in io.js?):
> const y = [1,2,3]
undefined
> y
[ 1, 2, 3 ]
> y.reverse()
[ 3, 2, 1 ]
> y
[ 3, 2, 1 ]
That concludes this experimentation-heavy post on constants. To summarise:
- Constants are variables that can't be changed (except by mutator methods)
- You can't define a constant as the property of an object (though I wish you could)
- Reassigning a constant has no effect (but doesn't throw an error)
- Redefining a constant causes an error to be thrown
- Deleting a constant has no effect and returns false
Hopefully this was useful to someone. Next time, I might take a look at some of the new additions to the Math object while I try and get my head around destructuring.