First principles

1. Code is executed sequentially

  • So let’s look at the code
console.log(showname);
// Error!!

var myname = 'a';
console.log(myname);
//a

console.log(myname);
var myname = 'a';
//undefined
Copy the code

Var myname = ‘a’;

  • The code is executed sequentially

So why does the following code say undefined instead of an error?

  • The variable has gone up

So what is variable promotion?

var myname = 'a';
/ / = = ="
var myname=undefined;
myname='a';
Copy the code

The declaration of a variable is promoted to the top of the current scope (global) while the assignment of a variable is not, so the variable is given the default value undefined.

  • Code is compiled before execution

The declaration of a variable is the compile phase, while the assignment and output of a variable are the execution phase. Although myName is declared, its assignment is after the output.

2. Minor escalation

showName();
// You can imagine the direct error!
Copy the code
showName();
function showName(){
    console.log('MyshowName')}//MyshowName
Copy the code

The showName function is executed first, then declared, in code order. So why is it still possible to print the results? Does the function get promoted?

  • Yes, the declaration part of the function is also promoted to the beginning of the code
// function showName(){
// console.log('MyshowName')
//}=== ""
function showName = function(){ 
    console.log('MyshowName')}Copy the code

When a function is compiled, the entire function is compiled

  • But if you use a functional expression, right?
showName()
var showName = function(){  
    console.log('showName')}/ / an error! showName is not a function
Copy the code

ShowName is declared as a variable, and the function is not compiled. Only when a function is declared will the entire function be compiled at compile time.

3. Promote again

  • Look at the topic
showName();
var showName = function(){
    console.log(2);
}
function showName(){
    console.log(1);
}
showName();
Copy the code

Find the output

Answer: 1, 2

Let’s translate the code equivalently

function showName(){
    console.log(1);
}

showName();/ / 1

// var showName = function(){
// console.log(2);
//}=== ""
var showName;
showName=function(){
    console.log(2);
}

showName();/ / 2
Copy the code

conclusion

  1. The code must run line by line
  2. The code is compiled and then executed
  3. Learn to distinguish between code that is run at compile time, such as variable declarations. Which code is the code that runs during execution, such as the assignment of a function

Beginners, still ask everybody big guy to give more advice!! 🙏