The ‘var’ Statement

While the var statement is not new to ES6, I strongly recommend reading through this refresher to help us better understand the concepts that the const and let statements introduce.

At its core, the var statement allows us to define, update and redefine variables. Variables declared with var are considered function scoped.

Define and Update

We can define and update variables declared with var without any errors.

var test = 100; console.log(test);

// Output: 100 test = 200; console.log(test);

// Output: 200

Redefine (Allowed)

We can also define an entirely new variable with the same name to override our previous variable with no errors.

var test = 100; console.log(test);

// Output: 100 var test = 200; console.log(test);

// Output: 200

Scope

Variables defined using var are scoped as follows:

Function scoped if they are defined within a function making them accessible only inside the function in which they are defined.

Globally scoped if they are not defined within a function making them accessible everywhere.

Consider the following example:

function scopeTest() {

var test = 100;

console.log(test);

} scopeTest();

// Output: 100

The test variable is considered a local variable, function scoped to the scopeTest() function. We are able to access the value stored in the variable test as both the variable declaration and the console.log() exist within the same scopeTest() function.

Using a modified version of this example allows us to illustrate how this variable is not accessible outside of the function it is scoped to:

function scopeTest() {

var test = 100;

} scopeTest(); console.log(test);

// Output: [Error] 'test' is not defined.

We are also allowed to update a variable at a higher scope to gain access to the value outside of the function. For reasons beyond the scope of this article, this is often considered bad practice and should be avoided unless absolutely necessary.

var test; function scopeTest() {

test = 100;

} scopeTest(); console.log(test);

// Output: 100

The “bad” side to var

So why bring in the new const and let statements in ES6? Because any variable defined outside of a function using var is globally scoped.

Global scoping is bad as it introduces: