var
allow to define and initialize a variable in JavaScript.
We say that var
is function-scoped, or globally-scoped if not used inside a function.foo
creates a new function scope.
Variables declared with var
inside this function are scoped to the function, meaning they are not accessible outside of it.var a = 10
; declares a variable a and initializes it to 10
.a
is declared inside a block, it is accessible outside the block because var does not respect block scope.var a = 1;
declares a variable a inside the function foo
and initializes it to 1
.foo()
when we invoke the function foo
, it creates the variable within its scope. However, after the function execution completes, a
is not accessible outside the function scope.var
. Use let
instead.
Read the next paragraphs to understand the reason of this statement{ ... }
creates a block scope.
Variables declared with let
(and const
) are scoped to the block they are declared in.var
, when we use let
, a variable defined inside a block will not be visible outsidelet a = 10
; declares a variable a and initializes it to 10
within the block scope.a
is only accessible within the block it is declared in. It is not accessible outside this block.a
is not available outside the function, just as happened with var
var
and let
in a for
loop:var
is used in a for
loop, the variable i
is hoisted to the function scope (or global scope if not in a function), making it accessible outside the loop.var i
is accessible outside the for
loop, so console.log(i)
prints 3
after the loop completes.let
is block-scoped.let
is used in a for
loop, the variable i
is scoped to the block of the loop itself.let i
is not accessible outside the for loop, so console.log(i)
results in a ReferenceError
, indicating i
is not defined outside the loop. This is the right behavior we expectvar
and let
:var
are hoisted with a default value: undefined
let
and const
are hoisted without a default initialization instead.var
and, as you can see, the first console.log
will display undefined
let
and when you try to get its value before its initialization you'll generate an error