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
?
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.
This won't generate a compile error:
This will:
Function VS block scope:
The main difference between
var
andlet
is that variables declared withvar
are function scoped. Whereas functions declared withlet
are block scoped. For example:variables with
var
:When the first function
testVar
gets called the variable foo, declared withvar
, is still accessible outside theif
statement. This variablefoo
would be available everywhere within the scope of thetestVar
function.variables with
let
:When the second function
testLet
gets called the variable bar, declared withlet
, is only accessible inside theif
statement. Because variables declared withlet
are block scoped (where a block is the code between curly brackets e.gif{}
,for{}
,function{}
).let
variables don't get hoisted:Another difference between
var
andlet
is variables with declared withlet
don't get hoisted. An example is the best way to illustrate this behavior:variables with
let
don't get hoisted:variables with
var
do get hoisted:Global
let
doesn't get attached towindow
:A variable declared with
let
in the global scope (which is code that is not in a function) doesn't get added as a property on the globalwindow
object. For example (this code is in global scope):Use
let
overvar
whenever you can because it is simply scoped more specific. This reduces potential naming conflicts which can occur when dealing with a large number of variables.var
can be used when you want a global variable explicitly to be on thewindow
object (always consider carefully if this is really necessary).The accepted answer is missing a point:
Here is an example for the difference between the two (support just started for chrome):
As you can see the
var j
variable is still having a value outside of the for loop scope (Block Scope), but thelet i
variable is undefined outside of the for loop scope.