Perfection Kills Quiz (part 9)

Previous posts on Perfection Kills JavaScript quiz: 1, 2, 3, 4, 5, 6, 7, 8.

9)

var x = 1;
if (function f(){}) {
  x += typeof f;
}
x;

Correct answer: "1undefined".

This question is closely related to question 2 from the same quiz.

First of all, it's important to understand that function f(){} is a (named) function expression rather than a function declaration. This follows from the fact that the condition in an if statement should be an expression that evaluates to true or false. Also, the grouping operator, i.e. the parenthesis, can only contain an expression.

Now let's determine whether our function expression evaluates to true or false. The only values that would evaluate to false are  0, -0, null, false, NaN, undefined, or the empty string (""). All other values evaluate to true (see MDN). Hence, the function expression evaluates to true and the statement within the if block is executed.

The statement x += typeof f; within the if block is equivalent to x = x + typeof f;. f in the named function expression is the function name, and it's only available in the scope of the function itself. Since the statement x += typeof f; is outside of the function's scope, f is undefined and typeof f evaluates to the string "undefined". Due to automatic type conversion, the variable x is assigned the value "1undefined".

For the discussion of named function expressions, see the following resources: Named function expressions demystified by Juriy "kangax" Zaytsev, definition of function expression on MDN.

All posts on Perfection Kills JavaScript quiz: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14.