HTML and CSS Reference
In-Depth Information
The typeof Operator
JavaScript has a handy operator, typeof , which can tell you, as you'd guess, the type of its operator. Let's examine a
few of these:
> typeof 2
> typeof 2.14
> typeof Infinity
> typeof NaN
So far so good; as you might expect, all of these return the string “number”.
> typeof ""
> typeof "coconuts"
> typeof '2.4'
> typeof true
> typeof false
Strings and booleans also behave as expected. The challenge comes when looking at objects, undefined , and null .
> typeof {}
> typeof { key: "value" }
> typeof undefined
> typeof null
The issue is that null is treated as an object rather than its own type. This can be a problem when using the
typeof operator, so make sure only to use null in situations in which this isn't a concern.
Note as well that typeof makes no distinction between different kinds of objects; it just tells you whether a value
is an object. To distinguish between different types of objects, we have the instanceof operator.
The instanceof Operator
instanceof compares two objects and returns a boolean indicating whether the first inherits from the second.
Let's look at a few examples:
> String instanceof Object
> Object instanceof String
Search WWH ::

Custom Search