ES6+ : var, let and const for variable declarations in JavaScript

var, let and const are keywords used to declare variables in javascript.  var and let describes about the access level (or scope) of the declared variable and const keyword determine whether the value of a variable can be re-assigned.  as the name implies, const keyword is used to declare constant in javascript program. we will look at them in detailed in the following sections.

 

Global and Local  variable declaration with var

var keyword is used to declare the variable in javascript. The most of the resources says that var is used to declare a global variable (globally accessible variable) in javascript. I cannot completely agree with this statement as the access level/scope is determined by the place where the variable is declared.

How to determine the variable scope or access level?

  • If the variable is declared outside a function, it can be used by any function within the same scope. Therefore the variable scope is global (for any function).
  • In the variable is declared inside a function, then it can be accessible only within that method. Therefore the variable scope is known as local (only for that function).

 

Global Scope

Please refer the below example where the “age” has been declared to be a global scope variable.

var age = 20;

function printAge() {
    console.log("age is " + age);
}

function printAgeCategory() {
    if (age >= 18) {
        console.log("adult");
    }
    else {
        console.log("child");
    }
}

printAge(); // will print "age is 20"
printAgeCategory(); // will print "adult"

 

Local Scope

Please refer the below example where the “age” has been declared to be a global scope variable (only for printAge function).

function printAge() {
    var age = 20;
    console.log("age is " + age);
}

function printAgeCategory() {
    if (age >= 18) {
        console.log("adult");
    }
    else {
        console.log("child");
    }
}

printAge(); // will print "age is 20"
printAgeCategory(); // Uncaught ReferenceError: age is not defined

 

printAgeCategory cannot access the age variable as it is declared within the printAge function. it has the local scope within the printAge function and can be accessed only within that function.

 

What is the reason behind introducing let in ES6?

After going through the above example, i am pretty sure that you have the following feeling and you might be questioning yourself about the reason behind “let” keyword for declaring variables.

You might be thinking of “var keyword can be used to declare variables which can have either global or local access. So, why do we need an additional variable declaration keyword like “let“?  What is the real usage of it ?”

 

Let me explain. 

 

Consider the below example.

for (var index = 0; index < 3; index++) {
    console.log("inside for loop [" + index + "]");
}

console.log("outside for loop [" + index + "]");

 

The result/output of above example can be given as follows.

inside for loop [0]
inside for loop [1]
inside for loop [2]
outside for loop [3]

 

Did you notice a wired behaviour by examining about output?  Can you notice that variable index is accessed from outside of the for loop ?  Isn’t it wired?  It is intended to be developed as local variable inside the for loop block. but unfortunately it is not. The solution is to move forward with block scope variables.

ES6 (ECMAScript 2015) has identified above issue and has introduced block scope variable declaration with “let” keyword.

 

“let” keyword for variable declaration in ES6

 

let keyword helps to declare block-scope variables. These variables are scoped in the braces {} (block) .

So the above program can be re-written with let keyword as follows.

for (let index = 0; index < 3; index++) {
    console.log("inside for loop [" + index + "]");
}

console.log("outside for loop [" + index + "]");

 

The result will be as follows.

inside for loop [0]
inside for loop [1]
inside for loop [2]
Uncaught ReferenceError: index is not defined

 

Since the index variable is declared with let, it has the blocked scope within the for loop. Therefore it cannot be accessed outside of the for loop. Trying to access it outside from the block may throw ReferenceError.

 

const

As the name implies the const keyword is used to define constants. The value for the constant should be assigned when it is declared and it cannot be changed/reassigned later.

Const actually means that once the variable is assigned it cannot be assigned again and an attempt to do so will throw an error.

const defends the variable from being overwritten.

const i = 0;
i = 1; // TypeError: Assignment to constant variable.

 

const, like let, is block scoped.

consider the below code segment which tries to reassign a value for the const variable.

if (true) {
  const i = 0;
}
console.log(i); // ReferenceError: i is not defined

 

const does allow mutability: the value can change if it’s mutable, such as an Object or an Array.

const obj = {
  i: 0
};
obj.i = 1; //here it is legal because we are not going to assign new object to 'obj'
obj.i; // 1  (legal and prints '1')

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s