What are ES6 variables?

Overview

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.

The var scope

The 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.

The let scope

The 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.

The const scope

The const method has a block scope, like the let method, but cannot have reassignment of value, array, or object. However, their element can change.

Code

Variable declaration

Explanation

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.

Free Resources