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
"number"
> typeof 2.14
"number"
> typeof Infinity
"number"
> typeof NaN
"number"
So far so good; as you might expect, all of these return the string “number”.
> typeof ""
"string"
> typeof "coconuts"
"string"
> typeof '2.4'
"string"
> typeof true
"boolean"
> typeof false
"boolean"
Strings and booleans also behave as expected. The challenge comes when looking at objects, undefined , and null .
> typeof {}
"object"
> typeof { key: "value" }
"object"
> typeof undefined
"undefined"
> typeof null
"object"
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
true
> Object instanceof String
False
 
Search WWH ::




Custom Search