What is the difference between let and var to declare a variable

Posted By : Himanshu Khurana | 23-Jun-2017

Scope is a accessibility of variables, functions, and objects in some part of your code during runtime. In other words, scope determines the visibility of variables and other resources in your code.

 

Variables is like a container. You can place data in container and  then refer to the data by naming the container. Before you use a variable in a JavaScript function, you must declare it. Variables are declared with "var keyword".

 

Let is same as a variable. You can declared the let variables with "let keyword".

 

You can see the difference below :

 

Var scope is a function scope or declared outside any function or global and let is included in the ECMA script 6th Edition in purpose to define variable this scope is a block level scope. Var variable can be used in the window scope and let variable cannot be used in windows object because they can not be globally accessed.You can see the example below :

//var
for(var i=0; i<5; i++){
    console.log(i)
}
console.log('outside', i) // 5


//let
for(let i=0; i<5; i++){
    console.log(i)
}
console.log('outside', i) // i is not defined

 

I hope this blog has been helpful to understand the difference between var and let.

 

THANKS

About Author

Author Image
Himanshu Khurana

Himanshu is an experienced Frontend developer with experience and capabilities to build compelling UI's for Web and Mobile Applications. Himanshu likes playing cricket and listening music.

Request for Proposal

Name is required

Comment is required

Sending message..