javascript interactive

JavaScript Interactive — a console crash course


1.3 Type Checking

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.

JavaScript only checks types in run-time. Dynamic type checking in code is available by using one of two operators:

  • typeof(value) – Returns a string with the primitive type of a value.
  • value instanceof Object – Checks if a value has a specified object type.
>>>
typeof(Object.notDefined)
"undefined"
>>>
typeof(null)
"object"
This is a common pitfall. Learn to live with it.
>>>
typeof(true)
"boolean"
>>>
typeof(42)
"number"
>>>
typeof("")
"string"
>>>
typeof({ key: 'value' })
"object"
>>>
typeof([1, 2, 3])
"object"
The typeof operator returns "object" for all object types.
>>>
[1, 2, 3] instanceof Array
true
>>>
[1, 2, 3] instanceof Object
true
All object type values are naturally also instances of Object
>>>
42 instanceof Number
false
Primitive types, like number, are not the same as their wrapper object types (e.g. Number).
>>>
typeof(function () {})
"function"
Functions are really object types, but the typeof operator isn't quite consistent with the type model...
>>>
(function () {}) instanceof Object
true
>>>

Index 1 2 3 4 5 6 7