Perfection Kills Quiz (part 13)

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

13)

function f(){ return f; }
new f() instanceof f;

Correct answer: false.

In this snippet of code, the instanceof operator checks whether the left operand new f() has the object f.prototype in its prototype chain.

Let's go through the code that runs when the left operand new f() is evaluated:

1) Function f is invoked in the "construction mode";
2) A new object is created, inheriting from f.prototype, and this keyword is bound to the newly created object (source). The interpreter inserts the line

this = Object.create(f.prototype);

as the first line of the function body.
3) Function f returns its return value. In this case, its return value is the function f itself.

The newly created object (described in step 2) is constructed in such a way that it has the object f.prototype in its prototype chain. The problem is that function f never returns this object. Instead, it returns function f, which does not have f.prototype in its prototype chain. For this reason, the snippet of code evaluates to false.

If there was no explicit return statement in function f, the result would have been true.

function f(){}
new f() instanceof f; //true 

If a function does not have an explicit return statement and is run in the "construction mode", it returns the newly created object inheriting from f.prototype.

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