What are the differences ? When should let be used over var ?
The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block.
However, global variables defined with let will not be added as properties on the global windowobject like those defined with var.
They are identical when used like this in a function block.
Here is the difference. let is only visible in the for() loop and var is visible to the whole function.
Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not:
let can also be used to avoid problems with closures. It binds fresh value rather than keeping an old reference as shown in examples below.
Every single click handler will refer to the same object because there’s only one counter object which holds 6 so you get six on each click.
General workaround is to wrap this in an anonymous function and pass i as argument. Such issues can also be avoided now by using let instead var as shown in code below.
DEMO (Tested in Chrome and Firefox 50)
The accepted answer is missing a point:
let is interesting, because it allows us to do something like this:
Which results in counting [0, 7].
Only counts [0, 1].
It also appears that, at least in Visual Studio 2015, TypeScript 1.5, "var" allows multiple declarations of the same variable name in a block, and "let" doesn't.
Wikitechy Rated 5 / 5 based on 378284 reviews.
World's No 1 Animated self learning Website with Informative tutorials explaining the code and the choices behind it all.