I came across this JavaScript quiz on a very cool blog and since I really enjoy solving such problems, I took the quiz. The result was humbling, and I was eager to find out why I got some of the questions wrong. I figured out why each problem behaves the way it does so I put them together for others below.
1
2
3
| 1. (function(){ return typeof arguments; })(); |
(a) “object” (b) “array” (c) “arguments” (d) “undefined”
The answer is (a). The arguments array is of type “object”. My first instinct was to think its an array, until I realized there was a typeof to be considered.
1
2
| 2. var f = function g(){ return 23; }; typeof g(); |
(a) “number” (b) “undefined” (c) “function” (d) Error
This results in an error because the function g has been assigned to the var f. So the answer is (d)
1
2
3
4
| 3. (function(x){ delete x; return x; })(1); |
(a) 1 (b) null (c) undefined (d) Error
I made the mistake of assuming I could delete x, but apparently you cannot delete arguments inside a function. So the answer is 1 which is option (a).
1
2
| 4. var y = 1, x = y = typeof x; x; |
(a) 1 (b) “number” (c) undefined (d) “undefined”
The answer here is “number”, because after assigning a value of 1 to y, x is also assigned that value. Doing a typeof on 1 obviously yields “number”.
1
2
3
| 5. (function f(f){ return typeof f(); })(function(){ return 1; }); |
(a) “number” (b) “undefined” (c) “function” (d) Error
Notice that we pass a function which returns 1 to the function f, which inturn executes the passed function and evaluates the type of the returned value. So typeof 1 results in “number” which is option (a)
1
2
3
4
5
6
7
| 6. var foo = { bar: function() { return this.baz; }, baz: 1 }; (function(){ return typeof arguments[0](); })(foo.bar); |
(a) “undefined” (b) “object” (c) “number” (d) “function”
This returns “undefined” because when the foo.bar function is executed, “this” refers to the window scope which ofcourse knows nothing about baz. How do you fix this?
Remember how to use JavaScript’s call() and apply()? If not, check here
In this case, we need to specify the “this” to be the object “foo”, like this:
Remember how to use JavaScript’s call() and apply()? If not, check here
In this case, we need to specify the “this” to be the object “foo”, like this:
1
2
3
4
5
6
7
| var foo = { bar: function() { return this.baz; }, baz: 1 }; (function(){ return typeof arguments[0].call(foo); })(foo.bar); |
1
2
3
4
5
| 7. var foo = { bar: function(){ return this.baz; }, baz: 1 } typeof (f = foo.bar)(); |