"JavaScript Advanced Programming" Chapter 7 Functions, regarding the promotion of function declarations, there is such an example:
if(condition){ function sayHi(){ alert("Hi!"); } } else { function sayHi(){ alert("Yo!"); } }
The original text in the book says:
On the surface, the above code means that when condition is true, use one definition of sayHi(); otherwise, use another definition. In fact, this is invalid syntax in ECMAScript, and the JavaScript engine will try to correct the error and convert it into a reasonable state. But the problem is that browsers are inconsistent in their attempts to correct errors. Most browsers will return the second statement, ignoring condition; Firefox will return the first statement if condition is true. Therefore this usage is dangerous and should not be used in your code.
But I tested it in chrome and js bin and changed the condition to true, and it could alert "Hi". There was no problem like "most browsers will return the second statement and ignore the condition" mentioned in the book. ,Why is this:
if(true){ function sayHi(){ alert("Hi!"); } } else { function sayHi(){ alert("Yo!"); } } sayHi();// Hi!
Please advise, thank you!
true is a literal, not a variable. The browser will directly optimize your if statement when parsing, similar to this:
However, the author is referring to another situation
After the compiler gets this code, it finds that there are two duplicate function declarations in the same scope. The first declaration will be directly replaced by the second declaration.
js does not recommend declaring functions inside blocks.
In strict mode, this code reports an error directly.