console.log(e());//error
if(true){
function e() {
return 10;
}
}
if(true){
function e() {
return 10;
}
}
console.log(e());//10
If the function declaration promotion is only promoted to the if scope, then what is the reason for the above? (Chrome58 test) Why can the function in the scope of if be accessed from the outside? Please give me the answer
This is actually a historical issue...
Previously in ES5, the specification stipulated that functions could only be declared in the top-level scope and function scope, and not in the block-level scope. Therefore, statements like this are actually illegal:
But in fact, all major browsers do not comply with this specification due to compatibility considerations.
In the current ES6 era, the specification stipulates the existence of block-level scope, and functions can be defined in block-level scope.
But in fact, things are not that simple, because in this case, the defined behavior of the function will be incompatible with the past. In order to ensure compatibility with the past, ES6 stipulates in Appendix B that the browser implementation does not need to comply with the above regulations. Have your own way of behaving.
In ES6 browsers, they actually behave like this:
Allow functions to be defined in block scope
The function declaration will actually be similar to the function expression declared using
var
, and the function name will be promoted to the top of the current function scopeAt the same time, function declarations will also maintain the hoisting behavior in the block-level scope
For your first code, if you take a closer look at what error it reports, you will find that the error is like this:
Uncaught TypeError: e is not a function
.This error means that
e
is not a function. In other words, the variablee
exists, but it is not a function. Combining the three rules we mentioned above, it is easy to think that it actually runs like this:After variable promotion, it will become like this:
There is no need to mention the second piece of code.
The function declaration within the if statement will not be promoted, just like the function expression, so the first one is a syntax error, and the second one will output 10
Equivalent to =>