JavaScript Basics 06 - What is the difference between the let and var keywords?

Hello, friends, I am Lei Gong!
Learn a little bit every day and continue to learn the basics of JavaScript today. Here are the study notes.

1. The nature of variables

Memory: The place where data is stored in a computer, equivalent to a space.
The essence of variables: It is a space that the program applies for in memory to store data.

Insert image description here

2. The similarities and differences between let and var

2.1. Similarity
2.1.1. Let and var are both keywords.
2.1.2. Let and var are both used to define variables.

2.2. Differences
2.2.1. When let defines a variable, it must be defined first and then used.
2.2.2. Variables defined by var can be tried first and then defined.
2.2.3. Variable names defined by let cannot be repeated (in the same scope).
2.2.4. Variable names defined by var can be repeated.

3. Global scope

Variables declared globally (outside a function) have global scope.

Example:

var myName=“雷工笔记”;
//此处的代码能够使用  myName

function myFunction(){
    
    
    //此处的代码能够使用 myName
}

Global variables can be used anywhere in a JavaScript program.

4. Function scope

Variables declared locally (as opposed to outside the function, meaning within the function) have function scope.

Example:

//此处的代码不能够使用 myName

function myFunction(){
    
    
    var myName=“雷工笔记”;
    //此处的代码能够使用 myName
}

//此处的代码不能够使用 myName

Local variables can only be used within the function in which they are declared.

5. JavaScript block scope

Variables declared with the var keyword do not have block scope.
Variables declared inside block {} can also be accessed from outside the block.

Example:

{
    
    
    var myName="雷工笔记"let yourName="盗墓笔记";
}
//此处可以访问myName,不可以访问yourName;

6. Re-declare variables

Re-declaring variables with var can cause problems.
Redeclaring variables within a block also redeclares variables outside the block.

Example:

   var myName="雷工笔记"//此处myName为雷工笔记
{
    
    
    var myName="盗墓笔记";
    //此处myName为盗墓笔记
}
//此处myName为盗墓笔记

Using let to redeclare the variable avoids this problem.
Redeclaring within a block does not redeclare variables outside the block.

Example:

    let myName="雷工笔记"//此处myName为雷工笔记
{
    
    
    let myName="盗墓笔记";
    //此处myName为盗墓笔记
}
//此处myName为雷工笔记

The reason here is actually because var does not have the concept of a block, and similar problems will occur when used in a loop.

7. Postscript

From the above records, we can find that since let appears to solve some problems with var, then we must choose to use let.
Just like the software you usually use, you must choose to use the latest version. After all, most upgrades are done to make the application more convenient and to make up for the bugs found in the previous version.

Guess you like

Origin blog.csdn.net/u013097500/article/details/132701701