Search⌘ K
AI Features

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).

Javascript (babel-node)
var x=10;
if(x=="10"){
console.log("true");
}
else{
console.log("false");
}
var x=10;
if(x==="10"){
console.log("true");
}
else{
console.log("false");
}

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'

typeof x === "string"

Boolean

true, false

typeof x === "boolean"

Number (floating point)

-2.75, 0, 1, 1.0, 3.1e10

typeof x === "number"

Integer

-2, 0, 1, 250

Number.isInteger(x)

Object

{},

{num:3, denom:4},

{isbn:"006251587X," title:"Weaving the Web"}, {"one":1, "two":2, "three":3}

Excluding null: x instanceof Object

Including null: typeof x === "object"

Array

[], ["one"], [1,2,3], [1,"one", {}]

Array.isArray(x)

Function

function () { return "one"+1;}

typeof x === "function"

Date

new Date("2015-01-27")

x instanceof Date

RegExp

/(\w+)\s(\w+)/

x instanceof RegExp

Below, we can see an example of testing the Object type:

Javascript (babel-node)
// Excluding null
x = {};
y = {num:3, denom:4};
console.log(x instanceof Object);
console.log(y instanceof Object);
// Including null
a = null;
console.log(a instanceof Object);
console.log(typeof a === "object");

A summary of type conversions is given in the following table:

Type conversion

Type

Convert to string

Convert string to type

Boolean

String(x)

Boolean(y)

Number (floating point) 

String(x)

parseFloat(y)

Integer

String(x)

parseInt(y)

Object

x.toString() or JSON.stringify(x)

JSON.parse(y)

Array

x.toString() or JSON.stringify(x)

y.split() or JSON.parse(y)

Function

x.toString()

new Function(y)

Date

x.toISOString()

new Date(y)

RegExp

x.toString()

new RegExp(y)