ECMAScript 6 introduced the let
statement. I've heard it described as a "local" variable, but I'm still not quite sure how it behaves differently than the var
keyword.
What are the differences? When should let
be used over var
?
ECMAScript 6 introduced the let
statement. I've heard it described as a "local" variable, but I'm still not quite sure how it behaves differently than the var
keyword.
What are the differences? When should let
be used over var
?
Now I think there is better scoping of variables to a block of statements using
let
:I think people will start using let here after so that they will have similar scoping in JavaScript like other languages, Java, C#, etc.
People with not a clear understanding about scoping in JavaScript used to make the mistake earlier.
Hoisting is not supported using
let
.With this approach errors present in JavaScript are getting removed.
Refer to ES6 In Depth: let and const to understand it better.
Some hacks with
let
:1.
2.
3.
Getter and setter with
let
:What's the difference between
let
andvar
?var
statement is known throughout the function it is defined in, from the start of the function. (*)let
statement is only known in the block it is defined in, from the moment it is defined onward. (**)To understand the difference, consider the following code:
Here, we can see that our variable
j
is only known in the first for loop, but not before and after. Yet, our variablei
is known in the entire function.Also, consider that block scoped variables are not known before they are declared because they are not hoisted. You're also not allowed to redeclare the same block scoped variable within the same block. This makes block scoped variables less error prone than globally or functionally scoped variables, which are hoisted and which do not produce any errors in case of multiple declarations.
Is it safe to use
let
today?Some people would argue that in the future we'll ONLY use let statements and that var statements will become obsolete. JavaScript guru Kyle Simpson wrote a very elaborate article on why that's not the case.
Today, however, that is definitely not the case. In fact, we need actually to ask ourselves whether it's safe to use the
let
statement. The answer to that question depends on your environment:If you're writing server-side JavaScript code (Node.js), you can safely use the
let
statement.If you're writing client-side JavaScript code and use a transpiler (like Traceur), you can safely use the
let
statement, however your code is likely to be anything but optimal with respect to performance.If you're writing client-side JavaScript code and don't use a transpiler, you need to consider browser support.
Today, Jun 8 2018, there are still some browsers that don't support
let
!How to keep track of browser support
For an up-to-date overview of which browsers support the
let
statement at the time of your reading this answer, see thisCan I Use
page.(*) Globally and functionally scoped variables can be initialized and used before they are declared because JavaScript variables are hoisted. This means that declarations are always much to the top of the scope.
(**) Block scoped variables are not hoisted
Variable Not Hoistinglet
will not hoist to the entire scope of the block they appear in. By contrast,var
could hoist as below.Actually, Per @Bergi, Both
var
andlet
are hoisted.Garbage Collection
Block scope of
let
is useful relates to closures and garbage collection to reclaim memory. Consider,The
click
handler callback does not need thehugeData
variable at all. Theoretically, afterprocess(..)
runs, the huge data structurehugeData
could be garbage collected. However, it's possible that some JS engine will still have to keep this huge structure, since theclick
function has a closure over the entire scope.However, the block scope can make this huge data structure to garbage collected.
let
loopslet
in the loop can re-binds it to each iteration of the loop, making sure to re-assign it the value from the end of the previous loop iteration. Consider,However, replace
var
withlet
Because
let
create a new lexical environment with those names for a) the initialiser expression b) each iteration (previosly to evaluating the increment expression), more details are here.As mentioned above:
Example1:
In my both examples I have a function
myfunc
.myfunc
contains a variablemyvar
equals to 10. In my first example I check ifmyvar
equals to 10 (myvar==10
) . If yes, I agian declare a variablemyvar
(now I have two myvar variables)usingvar
keyword and assign it a new value (20). In next line I print its value on my console. After the conditional block I again print the value ofmyvar
on my console. If you look at the output ofmyfunc
,myvar
has value equals to 20.Example2: In my second example instead of using
var
keyword in my conditional block I declaremyvar
usinglet
keyword . Now when I callmyfunc
I get two different outputs:myvar=20
andmyvar=10
.So the difference is very simple i.e its scope.
If I read the specs right then
let
thankfully can also be leveraged to avoid self invoking functions used to simulate private only members - a popular design pattern that decreases code readability, complicates debugging, that adds no real code protection or other benefit - except maybe satisfying someone's desire for semantics, so stop using it. /rantSee 'Emulating private interfaces'