Perfection Kills Quiz (part 2)

Let's continue to explore the 'Perfection Kills' quiz.

2)

var f = function g(){ return 23; };
typeof g();

Correct answer: error.

There are two common ways two define a function in JavaScript.

i) With a function expression that is assigned to a variable. In this case, one defines a variable that refers to a function:

var fun = function () {};

This line of code is an assignment statement, and function () {} is is an (unnamed) function expression.

ii) With a function declaration:

function fun() {};

The two methods are almost equivalent. The only difference is that function declaration is hoisting the function definition (moving it to the top of the current scope).

In the quiz question, the function is defined with an assignment statement and not declared. What makes this question tricky is that the assignment statement uses a named function expression function g(){ return 23; }. g is the function name, and it's only available in the scope of the function itself (see MDN article, Parameters section). Since the second line of code in the snippet (typeof g();) is outside of the function body, both g() and typeof g() return an error. The expression typeof g would have evaluated to "undefined".

A great discussion of named function expressions can be found in this article by Juriy "kangax" Zaytsev.

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