console.log(f);//function f(){return 1}
function f(){
return 1
}
var f=2;
I previously thought that if a function and a variable have the same name, function declaration promotion will overwrite variable declaration promotion, and then I tested the following code
function f(){
return 1
}
var f=2;
console.log(f);//2
The output of console.log(f) will be different depending on the position. Who overwrites whom, or is there some other reason?
Please give me some explanation
First paragraph
Equivalent to=>
Second paragraph
Equivalent to=>
See
https://www.zhihu.com/questio...
When defining a function not in a block, hoist the function first and then the variable declaration. Refer to ECMAScript 5, section 10.5.
Examples are as follows:
The above output is function. It is not undefined. So first promote the function, and then promote the variable declaration.
The JS interpreter will first promote thevar
statement. Note that promotes the var declaration statement instead of the assignment statement.Then, the function declaration will be promoted. Therefore, the situation mentioned above will be formedFor the second case, I feel it has nothing to do with hoisting. Althoughvar f
is also improved, the key here is that it is output after executing the assignmentf = 2
. . Therefore, it is a good choice to prove that JS is a weakly typed language = =Maybe what I said is ambiguous, LZ, it’s better to read other people’s explanations
According to ecma standards, the function declaration is promoted first; but to be honest, no matter who is promoted first, the result is actually the same, did you know?
The first piece of code is variable promotion, var f=undefined, and the variable f points to function; the second piece of code assigns 2 to f according to the execution order of JavaScript.
When js is executed, it will be executed from top to bottom.
In this code, the function declaration function f and the variable declaration var f are promoted together, but the function declaration priority will be higher,
so the code becomes
f=2 (It belongs to assignment, the position remains unchanged but the variable declaration is improved)
Second code
You also use the above method to understand
and it is understood by the js engine as
The function f is overwritten by the variable f, so the output is 2
As ycloud said, the above reason is that "function definition promotion is only promoted to the block scope of if"
If the function definition is promoted only to the if block scope, then what is the reason for the above? (Chrome58 test) Why can functions in the if block scope be accessed from the outside?