JavaScript: typeof & when should you use it?

In this post, we will talk about JavaScript’s typeof operator. We will start with its’ purpose. Then discuss its’ flaws and finally see when should you use it.

typeof's usage doesn’t happen to match its’ initial purpose.

What is typeof?

The typeof operator is used to identify the type of an object. It always returns a String value, so you should always compare return value to a string.

// Examples
typeof 37;        // "number";
typeof true;      // "boolean"
typeof undefined; // "undefined"
typeof {};        // "object"

// Call with parentheses
typeof(37);        // "number";

As you can see above, there are 2 ways to call the method. typeof is an operand and not a function, that is why, the second method is actually not a function call. Operation in parentheses are evaluated and then passed to typeof.

So far, so good, we know its’ purpose. Now let’s see its’ flaws.

Flaws and caveats

I’ll just say it: typeof is one of the biggest flaws in JavaScript. It had only one job, to return the type of an object. But let’s see the table below (source):

Value               Class      Type
-------------------------------------
"foo"               String     string
new String("foo")   String     object
1.2                 Number     number
new Number(1.2)     Number     object
true                Boolean    boolean
new Boolean(true)   Boolean    object
new Date()          Date       object
new Error()         Error      object
[1,2,3]             Array      object
new Array(1, 2, 3)  Array      object
new Function("")    Function   function
/abc/g              RegExp     object   (function in Nitro/V8)
new RegExp("meow")  RegExp     object   (function in Nitro/V8)
{}                  Object     object
new Object()        Object     object
alert               Function   function (object in IE 6, 7, 8)
null                null       object   (in future ECMAScript versions)

"Type" column lists the typeof‘s return values and "Class" column shows the actual class of the operand.

As you can see, in most of the case you end up with object string instead of the actual class name. A workaround for getting the class of an object is to use Object.prototype.toString method. Here is how:

Object.prototype.toString.call("foo")      // [object string]
Object.prototype.toString.call(new String) // [object string]

As you can see, this is not the ideal return value. Here is a JavaScript function that would help make your code more readable (source):

function is(type, obj) {
    var clas = Object.prototype.toString.call(obj).slice(8, -1);
    return obj !== undefined && obj !== null && clas === type;
}

is('String', 'test');             // true
is('String', new String('test')); // true

If you want to check the type of an object, use Object.prototype.toString method instead of typeof operator. This would make your code behave as expected.

NOTE:
ECMAScript 5 changes the Object.prototype.toString method’s return values for null and undefined from object to null and undefined.

When should you use typeof?

typeof is good for checking if variables are undefined. If you make use of an undefined variable in your code, you will get a ReferenceError. Using typeof will not cause your code to throw an error.

if( typeof foo !== "undefined") {
    // defined
}else {
    // undefined
}

To conclude, unless you are checking whether a variable is defined or not, you should avoid using typeof.