What was the problem with var?

We already had the var keyword in JS for declaring variables. So why has ES6 introduced additional keywords?

To understand the problem in var , first you need to understand what scope is.

Scope determines the accessibility of variables, objects, and functions from different parts of the code. — w3schools

There are 3 types of scope in JavaScript:

Function (Local) Scope

Global Scope

Block Scope (new with ES6)

var supports function & global scope, but not block scope.

Function (Local) Scope

When a variable is defined inside a function, it will be local only for that function and can’t be used outside:

function local() {

var number = 1;



console.log(number); // 1 gets printed

} console.log(number); // undefined

Global Scope

When a variable is declared outside of a function, or without the var keyword then it will become Global and will be accessible from anywhere:

var number = 1; function local() {

console.log(number); // 1 gets printed

} console.log(number); // 1 gets printed

Block Scope

Everything inside curly braces { }, if-else cases and for loops are block-scoped. This is the part that var doesn’t support.

Let’s define a variable (with var ) inside the for loop and see what gets printed…

for(var i = 1; i < 10; i++) {

console.log(i);

} console.log(i); // What do we expect here?

Everything seems fine till here. But what about the second console.log?

The second console.log is outside of the for loop and the local variable “i” still gets printed, whereas it supposed to be undefined.

However, if we use let or const, since they are block-scoped, this problem will be solved.

Redeclaration issue of var

Another problem with var is that it allows redeclaring the same variables again and again:

var number = 1; // first declaration

var number = 2; // same variable redeclared with the same name console.log(number); // And we see no errors

Now let’s see how ES6 deals with them…

let instead of var

To prevent the problems I’ve mentioned above, let’s try again with let :

for(let i = 0; i < 10; i++) { // same local variable with let

console.log(i);

} console.log(i); // This time what do we expect?

So let supports block-scope and the second console.log returns undefined. Perfect!

Also, trying to redeclare a variable with let returns an error:

So the let keyword:

can be used instead of var

is block-scoped

doesn’t allow redeclaration, but can be reassigned later

Const

Another new keyword that ES6 brings is const .

“Constant: something that does not change.”

The difference between let and const is that, once we declare a variable with const , it cannot be changed later:

The const keyword: