let and const
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:
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 can not be re-assigned, the value is not immutable.
For example:
The read only nature can be demonstrated with any object:
Last updated
Was this helpful?