getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
Other
178.28k stars 33.43k forks source link

scope & closures Ch.4 #1677

Closed spencer17x closed 4 years ago

spencer17x commented 4 years ago

Yes, I promise I've read the Contributions Guidelines (please feel free to remove this line).


Please type "I already searched for this issue":

Edition: (1st or 2nd) 1st

Book Title: Scope & Closures

Chapter: Chapter 4: Hoisting

Section Title: Functions First

Question:

foo(); // "b"
var a = true;
if (a) {
   function foo() { console.log( "a" ); }
} else {
   function foo() { console.log( "b" ); }
}

in chrome, Why is this code wrong, it will be throwing a TypeError。Is it because of a browser update?

var a = 0;
if(true){
    a = 1;
    function a(){}
    a = 21;
    console.log("inner",a); // 21
}
console.log("outer",a); // 1

And how do I understand this code, the outer output 1, Is the function hoisted to block-level scope?

getify commented 4 years ago

See this section in the second-edition of this book:

https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch6.md#function-declarations-in-blocks-fib

spencer17x commented 4 years ago

@getify I read it, it means that I don’t have to dig into it, but try to avoid it?

getify commented 4 years ago

The best sense I can make of it is... yeah, just don't put function declarations inside of blocks.

spencer17x commented 4 years ago

Thank you very much for your answers.