The statement

I believe we all know that variable promotion, function promotion, can be the same name when how to deal with?

What is the output value of the two scenarios?

  1. The situation a
console.log(a);
var a = 100;
function a () {};
console.log(a);
Copy the code
  1. Scene two
console.log(a);
function a () {};
var a = 100;
console.log(a);
Copy the code

The answer is that the inputs are the same in both scenarios. The results are:

ƒ a () {}
100
Copy the code

Explanation:

Javascript has a pre-parsed code phase before executing it. At this point, functions and variables in the code will be identified first for promotion. Var declarations of variables and functions can be broken down into three steps: ① create, ② initialize, and ③ assign. For example, var a = 100;

  1. First create variable A;
  2. The secondInitialize theforundefined;
  3. The final value is 100

With that in mind, let’s take a look at what improvements are made to variables and functions during the pre-parsing phase.

  1. varthecreateandInitialize theBe promoted; inExecution phaseTo make theThe assignment;
  2. functionthecreate,Initialize theandThe assignmentWere promoted;
  3. letcreateBe promoted;
  4. Function declaration priority variable declaration;

Using this rule we can explain why the output of scenario 1 and scenario 2 is the same. Because the function takes precedence when the name is the same.

The interview is recommended

Three big summaries of this