Data Type Testing
Explore how to accurately test data types in JavaScript by using triple equality operators to prevent unintended type coercion. Learn about differences between literals and constructors for objects and arrays, and understand true empty objects and type conversions.
We'll cover the following...
How is testing done?
To test the equality or inequality of two primitive data values, we always use the triple equality symbol (=== and !==) instead of the double equality symbol (== and !=). Otherwise, for instance, the number 2 would be the same as the string "2" since the condition 2 == "2" evaluates to true in JavaScript.
Assigning an empty array literal, as in var a = [], is the same as invoking the Array() constructor without arguments, as in var a = new Array(). Assigning an empty object literal, as in var o = {}, is the same as invoking the Object() constructor without arguments, as in var o = new Object().
Notice, however, that an empty object literal {} is not really an empty object, as it contains property slots and method slots inherited from Object.prototype. So, a truly empty object (without any slots) has to be created with null as the prototype, like in var emptyObject = Object.create(null).
A summary of type testing code is given in the following table:
Type testing
Type | Example values | Test if x is of type |
String | "Hello world!", 'A3F0' |
|
Boolean | true, false |
|
Number (floating point) | -2.75, 0, 1, 1.0, 3.1e10 |
|
Integer | -2, 0, 1, 250 |
|
Object | {}, {num:3, denom:4}, {isbn:"006251587X," title:"Weaving the Web"}, {"one":1, "two":2, "three":3} | Excluding null: Including null: |
Array | [], ["one"], [1,2,3], [1,"one", {}] |
|
Function | function () { return "one"+1;} |
|
Date | new Date("2015-01-27") |
|
RegExp | /(\w+)\s(\w+)/ |
|
Below, we can see an example of testing the Object type:
A summary of type conversions is given in the following table:
Type conversion
Type | Convert to string | Convert string to type |
Boolean |
|
|
Number (floating point) |
|
|
Integer |
|
|
Object |
|
|
Array |
|
|
Function |
|
|
Date |
|
|
RegExp |
|
|