Before the inception of
var. However, with the
ES6, there are now three methods we can use to declare variables:
Each of these methods has its own scope. Let's see them.
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 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 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
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
View all Courses