Front-end

differences between var, let and const in ES6

October 31, 2017

Before ES6, there was only one way of declaring variables in JavaScript – var . But now, there are a couple of new ways to declare variables in ES6 – let, const.

Let’s do a quick review so you know the differences between var, let, and const.

1. var – function scope

Variable being declared using var will be function scoped, meaning it will exist inside the function it’s declared.

function  test () {

var age = 19;

console.log(age);      //19

}

test();

console.log(age);            // age is not defined

As you can see, age is not reachable from outside the function.

Other types of blocks — like if-statements, loops etc — will not be considered as a scope.

if (true) {

var age = 19;

}

console.log(age)  //19

age is reachable from outside the if-statement.

2. let and const – block scope

const is a signal that the identifier won’t be reassigned.

const age = 19;

age = 20;                            // Assignment to constant variable.

You can not change object or array, but you can change attribute of its.

const adam = {age: 19};

adam = {age: 20};             // Assignment to constant variable.

const adam = {age: 19};

adam.age = 20

console.log(adam)              // {age: 20}

let is a signal that the variable may be reassigned.

In ES6, let and const were introduced as another way to declare variables. Any block will be a scope.

Function still is a scope:

function  test () {

let age = 19;

console.log(age);      //19

}

test();

console.log(age);            // age is not defined

But in this case also other type of blocks qualifies as a scope, like if-statements.

if (true) {

let age = 19;

}

console.log(age)  // age is not defined

3. let in loops

for (var i = 0; i < 5; i++) {

setTimeout(function(){

console.log(i);

}, 1000);

}

Output:

5

5

5

5

5

Because a loop is not a scope when using var.

If you want output is 0 1 2 3 4, you can use let. Because let is block scope:

for (let i = 0; i < 5; i++) {

setTimeout(function(){

console.log(i);

}, 1000);

}

Output:

0

1

2

3

4

You Might Also Like