In js, variable promotion comes first or function promotion comes first?

Baidu"s article says that the function declaration is in the first place, and that the variable is in the first place, who is in the first place? Ask for advice

Jul.15,2021

Brother, the function belongs to the first-class citizen in JS, and the function comes before


.

variable promotion occurs in the process of creating a variable object. The function declaration is scanned first, and then the variable declaration is scanned. If the variable name is the same as the function already declared, nothing will happen. The variable declaration will not interfere with the existing attribute of the same name

console.log(name);// name(){console.log('cc');}
console.log(age);// age(){console.log(18);}
var name = 'cc';
function age(){
    console.log(18);
}
function name(){
    console.log('cc');
}

you can take a look at this JavaScript Foundation Series-execution Environment and scope chain


guess that it is interpreted and executed according to the writing order. Practice test


first variable promotion only occurs when var is declared, and there are not so many problems with let and const.
in addition, who comes first and then does not affect what, not hard to say who comes first, then it is a function, why? Because it's the norm.


promote in order, and the variables defined by function are assigned values during the promotion phase, so the later definition overrides the values of the variables defined earlier. The variable defined by var will not be assigned during the promotion phase, but will only be promoted. If the variable is already defined by another var or funciton during the promotion phase, it will not have any impact, so there is no problem of overwriting the previously promoted value. The var statement is not really assigned until the execution time, so the value of the console.log is actually the result of the execution time.

console.log(foo)
function foo(){
    console.log('bb')
}
function foo(){
    console.log('cc')
}
var foo = 'aa'
console.log(foo)

use let to prove that it is indeed promoted sequentially

function test(){
   function foo(){}
   let foo;
}
test(); //  let foo

function test2(){
   let foo;
   function foo(){}
}
test2(); //  function foo()

if the function is promoted first, then test2 should report an error on the second line.


  1. variables of the same name are declared only once
  2. function is a first-class citizen of js, and the declaration of the variable of the same name

is compiled first and overwritten

so what is printed is not undefined


function declaration is promoted first

for example:

console.log(foo)
var foo = 'aa'
function foo(){
    console.log('bb')
}
 
 foo() {
    console.log('bb')
}

 var foo = 'aa' 
Menu