Constants and Block Scoped Variables
ES6 introduces the concept of block scoping. Block scoping will be familiar to programmers from other languages like C, Java, or even PHP. In ES5 JavaScript and earlier, var
s are scoped to function
s, and they can "see" outside their functions to the outer context.
In ES5 functions were essentially containers that could be "seen" out of, but not into.
In ES6 var
still works that way, using functions as containers, but there are two new ways to declare variables: const
and let
.
const
and let
use {
and }
blocks as containers, hence "block scope". Block scoping is most useful during loops. Consider the following:
Despite the introduction of block scoping, functions are still the preferred mechanism for dealing with most loops.
let
works like var
in the sense that its data is read/write. let
is also useful when used in a for loop. For example, without let, the following example would output 5,5,5,5,5
:
However, when using let
instead of var
, the value would be scoped in a way that people would expect.
Alternatively, const
is read-only. Once const
has been assigned, the identifier cannot be reassigned.
For example:
The read-only nature can be demonstrated with any object:
However there are two cases where const does not work as you think it should.
A const object literal.
A const reference to an object.
Const Object Literal
The example above demonstrates that we are able to change the name property of object person, but we are unable to reset the reference person since it has been marked as const
.
Const Reference To An Object
Something similar to the above code is using a const
reference, below we've switch to using let for the literal object.
Take away, marking an object reference const does not make properties inside the object const.
Ref:.
Last updated