Before the inception of ES6
, there was only one way to declare variables in JavaScript: var
. However, with the ES6
, there are now three methods we can use to declare variables:
let
const
var
Each of these methods has its own scope. Let's see them.
var
scopeThe var
method has a function scope. This means that when we use it to declare a variable in a function, it belongs to the function. However, when we declare it outside the function, it has a global scope.
let
scopeThe let
method has a block scope. This means that when we use it to declare a variable in a block (expression), it belongs to that expression, and can't be accessed outside of it.
const
scopeThe const
method has a block scope, like the let
method, but cannot have reassignment of value, array, or object. However, their element can change.
To better understand the three forms of variable declaration in ES6
, let's play with the code above.
On line 14, we declare a test
variable using var
. Although we declare this variable inside of a for
loop, we can still access it outside it.
However, this changes when we change var
to let
. We observe that the same variable that is accessible when we use the var
syntax is not accessible outside the for
loop when we use the let
syntax or the const
syntax.