Previous posts on Perfection Kills JavaScript quiz: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
11)
(function(foo){
return typeof foo.bar;
})({ foo: { bar: 1 } });
Correct answer: "undefined".
This is also one of the easier questions of the quiz.
The anonymous function function(foo) {return typeof foo.bar;}
is immediately invoked with the argument { foo: {bar: 1} }
.
The foo in the body of the function refers to the parameter foo, which has the value { foo: {bar: 1} }
. Hence, foo.bar refers to the property 'bar' of this object. However, the object { foo: {bar: 1} }
does not have a property 'bar'. It has only one property 'foo' (and the value of this property is an object with the property 'bar', but 'bar' is not the property of the "original" object). For this reason, foo.bar is undefined. Since typeof undefined
is "undefined", the return value of our snippet of code is "undefined".
All posts on Perfection Kills JavaScript quiz: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14.