2

var y = 1;
if (function f(){}) {
    y += typeof f;
}
console.log(y);

I expected that the output would be '1function'. However, the actual output is '1undefined'. As far as I know, function declaration is hoisted and inside if statement has access to the function f. But why it printed out undefined as if function has not been declared?

nicovank
  • 3,021
  • 1
  • 18
  • 40
Jina
  • 29
  • 1
  • 4
    That is not a function declaration in the condition, it is a named function expression. The name of the function expression is available inside the function only, hence `f` in the example is not defined at all in the `if` block. If you tried to log `y`, you'd get an error. – Teemu Feb 15 '17 at 17:07
  • See also http://stackoverflow.com/questions/10069204/function-declarations-inside-if-else-statements – Sebastian Iorga Feb 15 '17 at 17:12
  • Ah... a typo, should've been "If you tried to log `f` ..." ofcourse. – Teemu Feb 15 '17 at 17:12
  • Out of curiosity, where have you found the snippet? Or are you just playing with JS? – Teemu Feb 15 '17 at 17:18

1 Answers1

2

You cannot declare a function inside a condition. As soon as you put the function declaration outside, before the if statement, you can use it in the condition and the result will be as you expected:

var y = 1;
function f(){}
  if (f) {
    y += typeof f;
  }
  console.log(y);

Edit: Well, turns out you actually CAN (sort of*), but not with the chosen notation. This will work:

var y = 1, f;
  if (f = function(){}) {
    y += typeof f;
  }
  console.log(y);

* as Teemu noted in the comments, this is not really a function declaration, but rather an anonymous function a reference to which is assigned to the variable f.

Constantin Groß
  • 9,010
  • 4
  • 17
  • 44