Saturday, April 18, 2020

Differences between var and let

#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.
See the execution context for more information.

The let variables

  • In the creation phase, thelet 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.

No comments:

Post a Comment