0. Address of supporting video tutorial

Bilibili: 10 minutes to disentrench var and let

1, the total is

There are three ways to declare quantities in JS, var, let, and const, including variable and constant declarations.

  • varConstants can also be declared in the same way as variables, but constants are a convention and not syntactically supported.
  • let: How to declare variables in the new version, andvarIt makes a big difference. It solves a lotvarThe remaining problems makejsThe language is more standardized and normalized.
  • const: Briefly mentioned hereconstJust remember two things:
    1. constWhen you declare a constant, you have to assign it.
    2. constDeclared constants cannot be reassigned. The other rules are equalletIt’s exactly the same.

2. The difference between var and let

2.1、 var

  • There are only global and function scopes, not block-level scopes
  • You can declare the same variable more than once in the same scope
  • Variables can be called before statements are declared

2.2、 let

  • There are not only global scopes and function scopes, but also block-level scopes
  • You cannot declare the same variable more than once in the same scope
  • Variables cannot be called before statements are declared

It’s easy to see the difference, just focus on the bold part above. The following are specific examples to illustrate one by one.

3, var and let distinction code examples

3.1 var has only global scope and function scope.There is noBlock-level scope

Block-level scopes are mentioned here, so let’s first look at what block-level scopes are. In terms of code representation, in addition to a pair of braces formed by the body of a function, such as loop statements, judgment statements, or even directly written braces, the area covered by these braces is block-level scope. But language support is another story.

Var declarations in early JS ignored this form of block-level scope and were only sensitive to global and function scopes.

In layman’s terms, variables declared by var are treated differently from variables with the same name declared inside and outside the function, while variables with the same name declared by var inside and outside the block scope are treated as the same variable.

3.1.1 Variables declared by var in the loop statement

for (var i = 0; i < 10; i++) {
  var one = 1;
}
console.log(one);
console.log(i);
Copy the code

Results:

> 1
> 10
Copy the code

The value of variable one can still be printed outside the circulation. It is because the loop body does not form block-level scope that variables are separated.

I’m also going to focus on the I variable, which is declared inside the parentheses.

Parentheses are usually used in arithmetic expressions to give precedence to operations. In this case, parentheses are used to separate the keywords for and var, and the syntax of the braces. Note: the parentheses are not operators, just syntactic constructs!

So you just have to separate it by parentheses and declare that the variable inside the parentheses is the same as the global variable, and of course you can print out the last value of I, and of course I is 10 because of the loop 10 times. It also shows that each loop is sharing a global variable I. This is important and can cause unexpected problems with DOM manipulation. There is an opportunity to publish a separate article on this issue.

3.1.2 Determine the variable declared by var in the statement

if (false) {
  var one = 1;
}
console.log(one);
Copy the code

Results:

> undefined
Copy the code

We know that if we print a variable that has never been declared, we will get an error, and the interpreter will tell us that the variable has not been defined. The code above cannot go inside the if statement because the condition is false.

If undefined is printed, the variable one must be declared, and the declaration of variable one via var will not be executed.

So declaring variable one is actually done for us by the interpreter’s precompilation process. When the interpreter executes a file, it will scan the entire line, extract all the declarations of variables and put them at the top of the code. This is called the declaration of variables and the assignment of variables stays the same. Equivalent to the following code.

var one
if (false) {
  one = 1;
}
console.log(one);
Copy the code

Results:

> undefined
Copy the code

In summary, precompilation helps us declare the one variable, but the one variable is not assigned a value of 1. The default value for declaring only unassigned variables is undefined.

Of course, if you change the judgment to true, the result will be 1, because the assignment is executed and 1 overwrites undefined.

if (true) {
  var one = 1;
}
console.log(one);
Copy the code

Results:

> 1
Copy the code

If you comment out the var statement inside the statement, you will still get an error that one is undefined. Why does the interpreter declare the one variable for us if there is no such action in the code file? Variable promotion is even more out of the question.

if (false) {
  // var one = 1;
}
console.log(one);
Copy the code

Results:

> ReferenceError: one is not defined
Copy the code

3.1.3 Function plus the variable declared by var in the judgment statement

Although var is blind to block-level scopes, it is sensitive to function scopes. Let’s look at examples of block-level scopes and function scopes together.

function printOne() {
  if (true) {
    var one = 1;
  }
  console.log(one);
}
printOne();
console.log(one);
Copy the code

Results:

> 1
> ReferenceError: one is not defined
Copy the code

Print one inside the function, and since the statement does not form a true block-level scope, it is perfectly possible to print one with the value 1.

If you print the value of one outside the function, it is blocked by the function scope, so you cannot get the value of one. If you print the value of one outside the function scope, you cannot find the value of one in the global scope.

3.2. Let not only has global scope and function scope,There areBlock-level scope

3.2.1 Variables declared by let in the loop statement

for (let i = 0; i < 10; i++) {
  let one = 1;
}
console.log(i);
console.log(one);
Copy the code

Results:

ReferenceError: i is not defined
ReferenceError: one is not defined
Copy the code

Both variables are not defined, of course, you need to print one by one, because the following code will not continue to execute after the error.

These two variables are not found because the let keyword is sensitive to block-level scope, so variables declared by let are valid only within the braces of the body of the loop. They are not seen globally, so an error is reported.

3.2.2 Determine the variables declared by let in the statement

if (false) {
  let one = 1;
}
console.log(one);
Copy the code

Results:

ReferenceError: one is not defined
Copy the code

Change the condition to true

if (true) {
  let one = 1;
}
console.log(one);
Copy the code

Results:

ReferenceError: one is not defined
Copy the code

Whether the condition is true or not, the result is that the variable one is not found or because of block-level scope.

3.2.3 Function plus variables declared by let in judgment statement

function printOne() {
  if (true) {
    let one = 1;
  }
  console.log(one);
}
printOne();
console.log(one);
Copy the code

Results:

ReferenceError: one is not defined
ReferenceError: one is not defined
Copy the code

Since one is declared in the block scope of the if statement, the value of one cannot be read either in the function or globally.

3.3 var can declare the same variable multiple times in the same scope

3.3.1 The global scope uses var to declare the same variable more than once

var user = 'xiaoming';
var user = 'xiaohua';
console.log(user);
Copy the code

Results:

xiaohua
Copy the code

Print normally and no error will be reported.

3.3.2 Function scope declares the same variable multiple times through var

function printUser() {
  var user = 'xiaoming';
  var user = 'xiaohua';
  console.log(user);
}
printUser();
Copy the code

Results:

xiaohua
Copy the code

Print normally and no error will be reported.

3.3.3 global scope declares the same variable multiple times through let

let user = 'xiaoming';
let user = 'xiaohua';
console.log(user);
Copy the code

Results:

SyntaxError: Identifier 'user' has already been declared
Copy the code

Error: The user variable has already been declared.

3.3.4 Function scope declares the same variable multiple times through let

function printUser() {
  let user = 'xiaoming';
  let user = 'xiaohua';
  console.log(user);
}
printUser();
Copy the code

Results:

SyntaxError: Identifier 'user' has already been declared
Copy the code

Error: The user variable has already been declared.

3.4. The variable declared by var can be called before the statement is declared

3.4.1 Global scope is called before variable declaration

console.log(user); 
var user = 'xiaoming';
Copy the code

Results:

undefined
Copy the code

In front of the variable is called, there is no error, but the print result is undefined, the reason is js interpreter before executing code, there will be a precompiled process, will scan code files of all variable declarations statement, then the front of the variable declaration to code, and the variable assignment statements the position unchanged, It’s called variable declaration promotion. So the code above is the same as the code below. The result must be undefined

var user; 
console.log(user); 
user = 'xiaoming';
Copy the code

Results:

undefined
Copy the code

3.4.2 Function scope is called before variable declaration

function printUser() {
  console.log(user); 
  var user = 'xiaoming';
}
printUser();
Copy the code

Results:

undefined
Copy the code

It is the same as the code below, except that the variables are promoted to the front of the function.

function printUser() {
  var user; 
  console.log(user); 
  user = 'xiaoming';
}
printUser();
Copy the code

Results:

undefined
Copy the code

3.4.3 Declare variables even in statements where conditions are false

function printUser() {
  console.log(user);
  if(false) {
      var user = 'xiaoming';
  }
}
printUser();
Copy the code

Results:

undefined
Copy the code

The above code looks like the user declaration cannot be executed, but the JS interpreter does not pay attention to the judgment condition, only looks for the declaration, sometimes promoted to the top of the function.

3.5. Variables declared by let cannot be called before statements are declared

3.5.1 Global scope is called before variable declaration

console.log(user); 
let user = 'xiaoming';
Copy the code

Results:

ReferenceError: Cannot access 'user' before initialization
Copy the code

The user variable cannot be accessed until it is initialized.

3.5.2 Function scope is called before variable declaration

function printUser() {
  console.log(user); 
  let user = 'xiaoming';
}
printUser();
Copy the code

Results:

ReferenceError: Cannot access 'user' before initialization
Copy the code

The error is the same as above, and the same is true inside the function.

4, summarize

Finally, summarize a simple and easy to remember rhyme

  • Var has no block, can be multiple sound, can be adjusted before
  • Let has block, no multiple voice, no leading tone