Difference Between Let and Var in Javascript with Example

We have started a tutorial series for developers who are curious to learn MEAN stack and become a Pro on the related technologies. Friends we all know that how the web technologies are changing in these days and how Javascript is making his presence every industry. So without wasting your time we are starting this series with the below Javascript basics.

Difference between Let and Var in depth

Before jump into the difference between Let and Var we should have little knowledge about the Scope. If you already familiar with it you can skip otherwise be with me.

What is Scpoe ?

In brief, basically scope is an area, range or we can say space where we can access that variable or object. We can easily understand the meaning of scope by looking into the below concept image. We know that the CTO of a company can access all projects and project managers that means CTO have global scope of that company. And the project manager can access only his own assigned projects that means project manager’s scope to his own projects.

Difference between let and var

I hope you are now clear about the scope here. Now come to the difference between Let and Var.

Difference according to global Scope.

If we declare let and var both similarly in global scope var variable will be added to window object where as “Let” will not get added to the global window object. Example

Example –

var a = "Hey, I love var.";
let b = "Hey, I love Let.";


// Output
console.log(window.a); // Hey, I love var.
console.log(window.b); // Undefined


Difference according to Function Scope

In this section how Let and Var variables will differ with each other in function.

let x =10; function withLetDeclaration()
{
let x = 100;
}
console.log(x); // Output 10



var x =10;
function withLetDeclaration()
{
var x = 100;
}
console.log(x); // Output 100

Difference according to Block Scope

Var can be accessed out side the Block scope where as Let cannot.

Example –

Let :
for(let x=0; x<10; x++){
// block scope
}
// Output
console.log(x) // Undefined;

Var :
for(var x=0; x<10; x++){
// block scope
}
// Output
console.log(x) // 10;


Conclusion :

I hope, the topic is cleared and now can use Let and Var without any fear and also can give answer in interviews. We can use Let or Var as per our choice and situations. I am giving two bonus question below please try and give answer. It will help to make the series interactive and interesting.

Bonus Question

What will be the out put of the below examples?

Let :
for(let x=0; x<10; x++){
setTimeout(function(){
console.log(x);
},2000);
}


Var :
for(var x=0; x<10; x++){
setTimeout(function(){
console.log(x);
},2000);
}

Leave a Reply

Your email address will not be published. Required fields are marked *