LET in ECMAScript 6 - Block Scoped Variables08 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 behavior with
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:
But when you use
const it looks another way.
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
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
ECMAScript 6 example:
const best practices
constvariable should become your default variable. (Read about const to know why)
letfor simple variables, which are had to be changed.
- It is good to use
forloops, because you always need block-scoped variable there
- Try to exclude
varfrom your code.