简体   繁体   中英

Javascript hoisting - David Shariff quiz

The question is, what will the following alert:

function bar() {
    return foo;
    foo = 10;
    function foo() {}
    var foo = '11';
}
alert(typeof bar());

and the answer is, function.

My questions:

  1. Isn't bar() being replaced by its return value? If no, why?
  2. Isn't foo = 10; being hoisted to the top? (hoisting)

You can look at it this way:

function bar() {
    var foo = function() {};
    return foo; // function ends here
    foo = 10;
    foo = '11';
}

The other two assignment statements aren't happening.

Only declarations are hoisted in JavaScript.

For function declarations, that includes their entire statement body (which is empty in the case of foo ). However, with var s, the assignments aren't considered part of the declaration and will remain where the statement was placed. (2)

To the engine, bar() appears to be:

function bar() {
    // hoisted
    function foo() {}
    var foo;          // no-op, `foo` was already declared by `function foo() {}`

    // remaining statements
    return foo;

    // unreachable code following a `return`
    foo = 10;
    foo = '11'; // separated from `var foo;`
}

The resulting typeof being function is referring to the type of function foo() {} , a reference to which is what bar() returns. (1)

alert(bar().toString()); // "function foo() {}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM