Difference between var and let in JavaScript
Mar 23, 2020 02:00 0 Comments ASP.net AJAX SATYALA ABHISHEK

                          Difference between var and let in JavaScript

          var and let are both used for variable declaration in javascript but the difference between them is that var is function scoped and let is block scoped.

 

1: Variable scopes

The var variables belong to the global scope or local scope if they are declared inside a function:

var counter;

The let variables are blocked scopes:

let counter;

 2: Creating global properties

The global var variables are added to the global object as properties. The global object is window on the web browser and global on Node.js:

var counter = 0;

console.log(window.counter); //  0

 

However, the let variables are not added to the global object:

let counter = 0;

console.log(window.counter); // undefined

 3: Redeclaration

The var keyword allows you to redeclare a variable without any issue.

var counter = 10;

var counter;

console.log(counter); // 10

If you redeclare a variable with the let keyword, you will get an error:

let counter = 10;

let counter; // error

4: The Temporal dead zone

The let variables have temporal dead zones while the var variables don’t. To understand the temporal dead zone, let’s examine the life cycles of both var and let variables, which have two steps: creation and execution.

The var variables

·         In the creation phase, the var variables are assigned storage spaces and immediately initialized to undefined.

·         In the execution phase, the var variables are assigned the values specified by the assignments if there are ones. If there aren’t, the values of the variables remain undefined.

The let variables

·         In the creation phase, the let variables are assigned storage spaces but are not initialized. Referencing uninitialized variables will cause a ReferenceError.

·         The let variables have the same execution phase as the var variables.

The temporal dead zone starts from the block until the let variable declaration is processed. In other words, it is where you cannot access the let variables before they are defined.

 

 

Prev Next
About the Author
Topic Replies (0)
Leave a Reply
Guest User

You might also like

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.


Let`s Connect