Talking about the duplicate names of variable names and function names in js

  • 2021-07-21 05:42:56
  • OfStack

Today, Sao Kai asked a question about the conflict of variable names, which was very interesting. By the way, he also reviewed some knowledge of pre-analysis. If there is something wrong, he forgot his predecessors to correct him. The question is as follows:


var a=100;
function a(){
    console.log(a);
}
a();

When this string code is executed, it will report an error: a is not a function

Here comes the question, why did you report this error? This involves the pre-resolution of functions and variables:

1) Function declarations are topped

2) Variable declarations are also topped

3) Function declarations are more topped than variable declarations: (Function is on top of variable)

4) The variable and assignment statement will be written from 1. When the js engine parses it, it will be divided into two parts: declaration and assignment, with the declaration at the top and the assignment remaining in the original position

5) Declared variables are not declared repeatedly

Knowing the above rules, the above code is equivalent to:


var a=function (){
    console.log(a);
}
var a=100;
a();

It is equivalent to re-assigning a, so an error will be reported.


Related articles: