1. I don’t understand the execution order of js. Execute the following code. When the alert is first started, a has not been declared. Shouldn’t an error be reported directly? Why is this function displayed first, then 10, then 3, and finally an error is reported? Shouldn't an error be reported from the beginning?
alert(a)
a();
var a=3;
function a(){
alert(10)
}
alert(a)
a=6;
a()
I asked my classmates and found out why that happened. First of all, we need to understand the concepts
1. In js, variable declarations and function declarations are made in advance, and function declarations are better than variable declarations. Therefore, alert(a) before declaring a will not report an error. Also, in the first alert, the function a appears, not the variable a.
2. The second alert, needless to say, just executes the function a.
3. The third alert, the result is 3, because before running here,
var a=3;
was executed. So a becomes 3.4. The last error was reported because a(); a was assigned twice. The first time was
var a=3;
, and the second time wasa=6;
, but no matter what, a was assigned It is not a function, so an error is reported.The first output
function
is due to hoisting.The second output 10 is the output of the second line
a()
.The third output 3 is the output of the third to last line
alert(a)
.The last error is from the last line
a()
. Because at this timea
has been reassigned to the number6
, which is no longer afunction
. Of course, an error will be reported when executinga()
.Is the variable declaration promoted? Just remember the following rules.
http://zonxin.github.io/post/...