Interview FAQ: typeof function

JavaScript type quirqs, and specifically typeof usage quirqs are popping up in Front End interviews in one form or another more often than you’d think.

So let’s have a look at one of these quirky scenarios.

We go into this knowing that typeof is a JavaScript operator which inspects the type of a given value and returns a string representing that type. We also know what JavaScript’s types are:

  • null
  • undefined
  • boolean
  • number
  • string
  • object
  • symbol (added in ES6)

Now, if we apply typeof to values of the above types, we mostly get the predicted behaviour, i.e. the strigified names of their types.

typeof null === "object"; //true
typeof undefined === "undefined"; //true
typeof true === "boolean"; //true
typeof 42 = "number"; //true
typeof "42" = "string"; //true
typeof { x: 1 } === "object"; //true
typeof Symbol() === "symbol"; //true (in ES6)

Everything looks as expected, apart obviously the crazy-looking typeof null === "object"; //true situation, a known JavaScript bug we discussed a while ago in another Interview FAQ entry. But now let’s take typeof a little further, and apply it to a function value.

typeof function foo() { /* ... */ } === "function"; //true

That certainly looks good, and much more natural than the typeof null behaviour, but it makes one wonder why function is not among JavaScript’s top level built in types.

The reason for that is that function is actually a subtype of object. Specifically, a function is actually defined as a callable object, which means an object with an internal call property which makes it invokeable. Further more, being objects, functions can have properties:

function foo(x, y, z) {
/* ... */

foo.length; //3 (the number of formal parameters we declared the function with)

That’s it for today, pretty awesome, huh? Now go and kill those interviews, peeps!