What to use? let, const or var in JavaScript

const and let are features of the new JavaScript ES6.

For variable declaration, instead of the old var we can now choose between const and let. const is for values that we don’t want to change and let is like the old var, where value can be changed later.

variable declared with var is function scoped. but variables declared with let and const are block scoped.

So, what is a block? A block is simply all the code that is wrapped inside curly braces {}, so each time we have a if statement, for block we are actually creating a new block.

Now, let’s see what it means with some example. the first code shows variable declared in old ES5 way with the var keyword and the second code shows variable declared in the new ES6 way with the let keyword.

//Old ES5
if(true){
    var b = 20;
}
console.log(b); //can be accessed outside the if block.
//New ES6
if(true){
    let b = 20;
}
console.log(b); //can't be accessed outside the if block.

So, you can clearly see that when we try to access the variable declared with the var keyword outside the if block there is no problem but if it is declared with the let keyword then it will throw an undefined variable error since we are trying to access it outside of the block and the variable simply does not exist there.

But what if we want to use the variable outside the block?

We will simply declare it outside the block.

let b;
if(true){
    b = 20;
}
console.log(b); //now it can be accessed.

Now let’s take another example, this time a for loop block.

//old ES5
var a = 100;
for(var a = 1; a <= 5; a++)
{
     console.log(a);
}
console.log(a);
1
2
3
4
5
6 //outside the for block

So, In the old ES5 code we have 1,2,3,4,5 from console logs inside the for loop and 6 from outside the for block. we can see that 100 is overwritten inside the for block as it is declared with var.

//new ES6
let a = 100;
for(let a = 1; a <= 5; a++)
{
     console.log(a);
}
console.log(a);
1
2
3
4
5
100 //outside the for block

and now, we have 1,2,3,4,5 which are the console logs inside the for loop. and then we get 100 which is defined before the for loop. So, that’s because of the block scope. the variable used in the for loop and before the for loop may be having the same name but actually are different variables.

Now let’s shift out focus on the const variable.

A const variable can’t be changed unlike the var variable.

//old ES5
var c = 10;
c = 20; //no problem
//new ES6
const c = 10;
c = 20; //can't be changed

A const variable must be defined on the same line while declaring.

//old ES5
var a; //no problem
a = 100;
//new ES6
const a ; //SyntaxError: missing = in const declaration
a = 100;

So, it must be like this

const a = 100;

Leave a Reply

Your email address will not be published.