LET in ECMAScript 6 - Block Scoped Variables
08 Jun 2016
let
has the same block scoping as const
, but let us look over Block Scoped Variables in ECMAScript 6
Understanding Block Scope
Let’s compare var
and let
behavior with this
:
It looks like let
variable has its own scope.
As you can see, var
scope is inside the function and let
scope is inside if-block.
Why does it happen?
Because when you write code like this:
The really thing Javascript doing is :
But when you use let
or const
it looks another way.
This code:
Becomes this:
for
loop
It is really not clever, that in JavaScript ES5 when you create a variable in a for
loop,
you can reach that variable out of that loop.
For example, if you had a variable with the same name it will be rewritten by a variable from inside a for
loop.
ECMAScript 5 example:
In ES6 this problem solves with let
variable, because it is block-scoped, so our new let
variable will be scoped to for
block.
ECMAScript 6 example:
let
and const
best practices
const
variable should become your default variable. (Read about const to know why)- Use
let
for simple variables, which are had to be changed. - It is good to use
let
infor
loops, because you always need block-scoped variable there - Try to exclude
var
from your code.var
is now the weakest signal available when you define a variable in JavaScript