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

8)

var f = (function f(){ return "1"; }, function g(){ return 2; })();
typeof f;

Correct answer: "number".

In order to understand this snippet of code, we have to look into the comma operator. A good explanation of the subject can be found here. According to MDN, "the comma operator evaluates each of its operands (from left to right) and returns the value of the last operand". Here is a simple example:

var y = ("abc", 5);
y; //5

Parentheses are needed in order to create a group and apply the comma operator before the '=' operator.

In our case, the expression (function f(){ return "1"; }, function g(){ return 2; }) evaluates to function g(){ return 2; }. As a result, the original snippet of code is equivalent to the following one:

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

Function function g(){ return 2; } is immediately invoked and returns 2. Hence, the variable f is assigned the value of 2 and typeof f is "number".

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