Variable promotion in JavaScript

When executed JSwhen the code is generated execution environment .

If the code is written in a function, the function execution environment will be generated , otherwise it will be in the global execution environment . There are only these two execution environments.

Look at the following piece of code:

b(); // call b
console.log(a); // undefined

var a = 'Hello world';

function b() {
    
    
    console.log('call b');
}

This is because functions and variables are promoted. The usual explanation for promotion is to move the declared code to the top.

But a more accurate explanation is that when generating an execution environment , there will be two stages:

The first stage is the creation stage, the JSinterpreter will find out the variables and functions that need to be promoted, and give them a good space in the memory in advance. If it is a function, store the entire function in memory. Variables are only declared and assigned values undefined.

In the second stage, the code execution stage, we can use it directly in advance.

In the promotion process, the same function will overwrite the previous function , and the function takes precedence over variable promotion:

b(); // call b second

function b() {
    
    
    console.log('call b fist');
}

function b() {
    
    
    console.log('call b second');
}
var b = 'Hello world';

Because it varwill produce many errors, it ES6is introduced in let. letBefore a statement can not be used, but this is not often said letnot improve.

letImproved , the memory has also opened up space for him in the first stage, but because of the characteristics of this statement, it cannot be used before the statement .

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/111930742