'YDNJS: scope and closures hoisting wrong example [duplicate]
I am reading YDNJS: scope and closures, And in chapter 4 which talks about hoisting it says that
Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this code implies
foo(); // "b"
var a = true;
if (a) {
function foo() { console.log("a"); }
}
else {
function foo() { console.log("b"); }
}
the author assumes that foo() will print 3 to console as the last function declaration override the previous one in the if block before the engine evaluates the condition.
The problem is that when I run this code on my own it throws a TypeError: foo is not a function instead of 3.
Solution 1:[1]
Conditionally created functions Functions can be conditionally declared, that is, a function statement can be nested within an if statement, however the results are inconsistent across implementations and therefore this pattern should not be used in production code. For conditional function creation, use function expressions instead.
var hoisted = "foo" in this;
console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`);
if (false) {
function foo(){ return 1; }
}
In Chrome: 'foo' name is hoisted. typeof foo is undefined
In Firefox: 'foo' name is hoisted. typeof foo is undefined
In Edge: 'foo' name is not hoisted. typeof foo is undefined
In Safari: 'foo' name is hoisted. typeof foo is function
Read more about it here link
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |