O'Reilly logo

JavaScript: The Good Parts by Douglas Crockford

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

typeof

The typeof operator returns a string that identifies the type of its operand. So:

typeof 98.6

produces 'number'. Unfortunately:

typeof null

returns 'object' instead of 'null'. Oops. A better test for null is simply:

my_value === null

A bigger problem is testing a value for objectness. typeof cannot distinguish between null and objects, but you can because null is falsy and all objects are truthy:

if (my_value && typeof my_value === 'object') {
    // my_value is an object or an array!
}

Also see the later sections "NaN" and "Phony Arrays."

Implementations disagree on the type of regular expression objects. Some implementations report that:

typeof /a/

is 'object', and others say that it is 'function'. It might have been more useful to report 'regexp', but the standard does not allow that.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required