Difference between var and let in JavaScript

Difference between var and let in JavaScript

Preface:

var is a variable declaration keyword that has existed since JavaScript first appeared, while let is a variable declaration keyword that only appeared in ES6. There is undoubtedly a big difference between the two. So what are the specific differences?

1. Scopes are expressed in different forms

var is function scope, let is block scope

{
  var monkey = 'Xun Wukong';
  let pig='Pork chop cover';    
}
console.log(monkey); //output undefined
console.log(pig); //Error: pig is not deined


As can be seen from the above code, variables declared with let are only valid in the code block in which they are located, and are invalid and inaccessible outside the code block, while variables declared with var are valid in the function scope in which the code block is located.

2. The difference between variable promotion and non-promotion

Variables declared with var will be hoisted, but variables declared with let will not be hoisted.

console.log(monkey); //undefined
var monkey = 'Xun Wukong';

console.log(pig); //Error: pig is not defined
let pig='Pork chop cover'; 


Following the same logic, why a variable declared with var is shown as undefined when called before it is declared, while a variable declared with let throws an exception when called before it is declared? This is the difference between the two in variable promotion. Variables declared with var have variable promotion, while variables declared with let do not.

So what is variable promotion? I will not give a conceptual description here. I will only say my personal understanding that the above code is actually equivalent to the following:

var monkey;

console.log(monkey); //undefined
monkey = 'Xun Wukong';

console.log(pig); //Error: pig is not defined
let pig='Pork chop cover'; 

Do you see the difference? The variable declared with var will be extracted to the top of the scope for definition but no value will be assigned. The assignment operation is still in your code, so when you call the variable declared with var , it is a variable that has been declared but has not been defined, so the result of the call is undefined . This is the so-called variable promotion. However, there is no such variable promotion for variables defined by let.

3. Differences in Temporary Dead Zones

Temporary dead zone: If a variable is let in a scope, and there is a variable with the same name in the outer scope, then even if the variable is changed in the scope, it will not affect the outer scope.

The specific performance is as follows:

for(var i=0;i<5;i++){
    setTimeout(function(){
        console.log(i)
    },1000)
}
for(let i=0;i<5;i++){
  setTimeout(function(){
     console.log(i)          
  },1000)  
}


What are the results of running these two codes?

The result of the first code is that 5 5s are printed in sequence after 1 second. The result of the second code is that 0, 1, 2, 3, 4 are printed in sequence after 1 second.

Why does this difference exist?

Because the variable i in the first code is declared by the var keyword, there is no critical dead zone, that is, the variable i you access in setTimeout after 1 second is the i after the for loop in the global context has finished running, so the printed results are all 5;

The variable i in the second code is declared by the let keyword, which creates a critical dead zone. The i variable in setTimeout is the value of i when you stored it at that time. The i in this storage interval will not change because there is the same i variable outside and it is assigned a different value. It is still the value stored before. This is the manifestation of a temporary dead zone, and it is also the reason why the second code prints 0, 1, 2, 3, 4 in sequence after running.

4. In the same context, var can be repeatedly declared, but let cannot

let monkey='Xun Wukong';
let monkey = '逼马吻'; //Error: Identifier 'a' has already been declared
var pig = 'Pork chop cover';
var pig = 'pig anal fissure'; //Normal access, the value of the variable pig is replaced

This is the end of this article about the difference between var and let in JavaScript. For more information about var and let in JavaScript, please search previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • What are the differences between var let const in JavaScript
  • Detailed explanation of the differences between var, let and const in JavaScript es6
  • Detailed explanation of the differences and usage of var in JavaScript and let and const in ES6 specifications
  • Understand the difference between let, var and const keywords in JavaScript
  • Detailed explanation of the difference between let and var declaration variables in js
  • A Brief Analysis of the Differences among var, let, and const in JavaScript

<<:  How to find and delete duplicate rows in MySQL

>>:  Example code for drawing double arrows in CSS common styles

Recommend

How to install a virtual machine with Windows services on Mac

1. Download the virtual machine Official download...

MySQL paging analysis principle and efficiency improvement

MySQL paging analysis principle and efficiency im...

Solution to slow network request in docker container

Several problems were discovered during the use o...

Seven Principles of a Skilled Designer (2): Color Usage

<br />Previous article: Seven Principles of ...

Vue detailed introductory notes

Table of contents 1. Introduction 2. Initial Vue ...

How to delete node_modules and reinstall

Table of contents Step 1: Install node_modules in...

Using iframe techniques to obtain visitor QQ implementation ideas and sample code

Today at work, a friend I added temporarily asked ...

Solution to index failure in MySQL due to different field character sets

What is an index? Why create an index? Indexes ar...

In-depth explanation of the locking mechanism in MySQL

Preface In order to ensure the consistency and in...

How to elegantly implement the mobile login and registration module in vue3

Table of contents Preface Input box component lay...

Vue implements graphic verification code login

This article example shares the specific code of ...

How to use CSS attribute selectors to splice HTML DNA

CSS attribute selectors are amazing. They can hel...