0

I'm reading the book "You don't know JS" and I read this part: enter image description here

What the author means here is that these foo functions will be hoisted at the global level since conditional statements don't have the ability to create their own scope in JS. So the expected behavior is that I will get b printed.

However the result is an error: "Uncaught TypeError: foo is not a function at :1:1"

However if I do this:

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

and then invoke the function I will get the result "a"?

BoSsYyY
  • 563
  • 5
  • 13
  • Well, the author didn't got it correct (or you didn't?). There is a feature called "Conditionally created functions", see [Function declaration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function) at MDN. The feature itself is not widely supported, afaik it was "officially" added to ES6, though e.g. FireFox has implemented it for years. – Teemu Jun 02 '18 at 17:28
  • The behavior the author describes is out of date. (That's twice in one day out-of-date behavior has come up in relation to "You don't know JS". The first involved behavior described in 2009, which was fairly shocking as "You don't know JS" was written well after that. This changed in ES2015, though.) – T.J. Crowder Jun 02 '18 at 17:33
  • @Teemu It's not a feature. It's included in the ES6 section about compatibility mode to define a consistent behaviour. In strict mode, it's still a plain error. (See the second duplicate for details) – Bergi Jun 02 '18 at 17:48
  • @Bergi - Using a function declaration as a statement isn't an error in strict mode. (The code above is, because `foo` isn't declared where it's used, but declaring functions in conditional blocks isn't.) – T.J. Crowder Jun 04 '18 at 06:19
  • @T.J.Crowder Yes, I meant using the function outside of its block scope is an error. – Bergi Jun 04 '18 at 09:41
  • @Bergi - Gotcha. – T.J. Crowder Jun 04 '18 at 09:51

0 Answers0