getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Scope & Closures - 2nd Edition - #35 - Correction needed in function hoisting line statement

slayercoder opened this issue · comments

I already searched for this issue
Edition: (1st or 2nd) 2nd
Book Title: You-Dont-Know-JS
Chapter: Chapter 5: The (Not So) Secret Lifecycle of Variables Line#35
Section Title:

Problem:
Can we elaborate the below statement little more, since I was going through the statement, I went through it twice and I was thinking to test a particular statement which is as below:
"One key detail is that both function hoisting and var-flavored variable hoisting attach their name identifiers to the nearest enclosing function scope (or, if none, the global scope), not a block scope."

When we say that function or var declared variables are attached to their nearest function scope or global scope but not the block scope, so the below code should be able to call the function

blockedScopeFunction();
console.log(blockScope);
if (true) {
    var blockScope = "I am blocked scoped";
    function blockedScopeFunction() {
        return true;
    }
}

Expected outcome as per above statement -

true
undefined

Actual output

scopes.js:1 Uncaught TypeError: blockedScopeFunction is not a function
    at scopes.js:1:1

Exists in below JS environments
Mozilla (103.0 (64-bit))
image

Chrome (Version 103.0.5060.134 (Official Build) (64-bit))
image

I think when code parsing is being done, the parsing phase it not able to look ahead of the if block and create a binding and register that variable with the function object as shown below,
image

I think we should be rephrasing the the above statement under consideration to make it more correct

This topic is called "Function in Block (FiB)" and is covered here: https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch6.md#function-declarations-in-blocks-fib

Indeed, the first paragraph of the immediate next section mentions that function-hoisting only applies outside blocks, and references that Chapter 6 section on FiB to explain.

This topic is called "Function in Block (FiB)" and is covered here: https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch6.md#function-declarations-in-blocks-fib

Yes this makes sense, I think I should have read one more paragraph, I stopped at that point and started POC, thanks @getify