Const / Let / Var                                                                                                Which One Should You Use?

Const / Let / Var Which One Should You Use?

Difference between var, let and const

Var

Let's define a function and call it hello. Inside the function, I defined a (for) loop, so for var i we set the value 0 and as long as it's less than 3, increment it by one then it should print the numbers on the console and I called the function at the end.

function hello(){
     for(var i=0; i<3; i++){
        console.log(i);
    }
}

hello();

Here is the browser console result!

screen04.jpg

In most of the programming languages, when we declare a variable, that variable should only be accessible in the block where it is defined that's what we call scope, however, here a console.log(i) is outside of the scope and it is still accessible.

function hello() {
  for (var i = 0; i < 3; i++) {
    console.log(i);
  }
  console.log(i)
}

hello();

We got i which is displayed because in the last iteration i became 3 and because 3 is not less than 3 we exit from the loop.

screen04.jpg

So when you declare a variable with the var keyword, that variable will be accessible inside the given function, and this is one of the weird points about javascript.

After 2015, two keywords were introduced by ES6, and that's let and const.

Let

let solved this problem, have a look!

function hello() {
  for (let i = 0; i < 3; i++) {
    console.log(i);
  }
  console.log(i)
}

hello();

When you declare a variable with let keyword, the variable is only accessible inside that block in which it is declared. let's see the result.

screen07.jpg

Here we got an error on the console, which is " i is not defined ".

Let me make it more clear, The variable that declares with var keyword is scoped to the function, however, the variable which is defined with let keyword is only scoped inside the block in which it is defined.

So, use let keyword unless you have a valid reason for defining var keyword.

Const

Another new keyword in ES6 is const and it is used to define a constant. const is also scoped inside the block in which it is defined, same like let, however, I show you the difference between let and const.

const x = 1;
 x = 2;

let's define a variable called x with const keyword and set it to 1, now we resign this to 2.

Let's see what we got!

screen05.jpg

You see, it's given an error that x is already defined. This means that the variable which is defined by the const keyword cannot be reassigned that's why we call it constant. Use const over let and use let only when you need to reassign the variable value.

I hope you find this useful :)