Perfection Kills Quiz (part 5)
Previous posts on Perfection Kills JavaScript quiz: 1, 2, 3, 4.
5)
(function f(f){
return typeof f();
})(function(){ return 1; });
Correct answer: "number".
The function f(f) {return typeof f();}
is immediately invoked with the argument function(){ return 1; }
.
The expression function f(f) {return typeof f();}
is a named function expression. The first f (outside the parenthesis) is the name of the function, which is available within the function local scope. The second f (in the parenthesis) is just a parameter, which is also available within the function local scope.
So what does the f in the body of the function refer to? There are two possible "candidates" for the value of f in this scope: function name f and the value of the parameter f, but of course f can refer to only one thing. In order to answer this question, one has to know where the function name is actually 'stored'.
I will quote a great article on named function expressions by the author of the Perfection Kills Quiz: "When named function expression is evaluated, a special object is created. The sole purpose of that object is to hold a property with the name corresponding to function identifier, and value corresponding to function itself. That object is then injected into the front of the current scope chain, and this 'augmented' scope chain is then used to initialize a function".
This means that the function name is an outer variable relative to the function local scope. The invoked function will first look for the variable f in its local scope, where this variable refers to the value of the parameter f.
Hence, f in the statement return typeof f();
refers to the argument of the invoked function. This argument is function(){ return 1; }
.
Important note: if the function parameter had a different name, f in the function body would have referred to the function itself.
Now let's evaluate typeof f()
. The f()
is equal to the return value of the function function(){ return 1; }
, which is 1. Then typeof f()
equals typeof 1
, i.e. "number".
All posts on Perfection Kills JavaScript quiz: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14.