Use typeof to Check JavaScript Data Types at Runtime

JavaScript is a dynamically typed language. In other words, the data type of JavaScript variables can change over the course of a program's execution. As a result, it can often be helpful to check the data type of a variable at runtime (as the code is executing) prior to performing an operation on said variable.

Primitive Data Types

JavaScript provides six built-in primitive types. (Primitives are types that are not objects.)

The boolean data type represents the values true or false:

var theSkyIsBlue = true;

var selfiesAreCool = false;

The number data type represents integer and floating point values:

var one = 1;

var pi = 3.14159265359;

The string data type represents textual data:

var movieTitle = 'Batman V Superman';

The null data type can only be represented as the value null. It's used to indicate the absence of a value:

var noValue = null;

The undefined type can only be represented as the value undefined. JavaScript developers typically avoid programmatically setting variables to undefined. When the JavaScript engine creates a variable in memory, it sets its value to undefined until it's assigned a value. We get undefined if we attempt to print the value of a variable that has not been assigned a value:

> var foo;
> console.log(foo);

undefined

The symbol type was introduced in the latest JavaScript standard, ECMAScript 6 (ES6). It is a unique and immutable data type. I won't go into detail on symbols here.

Objects

In addition to the primitive data types, JavaScript supports objects. Objects are complex data types that can have data (properties) and behaviors (functions/methods).

(Note that functions are objects that are given special treatment.)

JavaScript comes with several built-in objects, including objects that correspond to four of the six primitive data types (Boolean, Number, String, Symbol).

Use typeof to Check the Type of a Variable at Runtime

The typeof operator allows us to check the type of a variable at runtime.

typeof returns "boolean" when applied to a variable of type boolean:

> var isTheSkyBlue = true;
> typeof isTheSkyBlue;

'boolean'

typeof returns "number" when applied to a variable of type number:

> var pi = 3.14159265359;
> typeof pi;

'number'

typeof returns "string" when applied to a variable of type string:

> var movieTitle = 'Batman V Superman';
> typeof movieTitle;

'string'

typeof returns "undefined" when applied to a variable that either doesn't exist or whose value has not been set:

> typeof bar;

'undefined'

> var bar;
> typeof bar;

'undefined'

typeof returns "function" when applied to a function:

> function baz() {}
> typeof baz

'function'

What do you suppose will happen when typeof is applied to an array?

> var numbers = [1, 2, 3, 4, 5];
> typeof numbers;

'object'

It returns "object". The reason is because a JavaScript array is an object, and typeof returns "object" for all objects (except functions).

The same holds true for the object analogues of the primitive data types:

> var movieTitle = new String("Batman V Superman");
> typeof movieTitle;

'object'

> var one = new Number(1);
> typeof one;

'object'

(Note that use of the boolean, number, and string primitives are preferred to their object counterparts Boolean, Number, and String.)


Let's have a look at how what we've learned so far is applied in one of the most popular open source JavaScript projects.

typeof Examples in Node.js Utility Functions

Node.js is a server-side JavaScript runtime environment. It allows developers to build web applications entirely in JavaScript.

Node.js comes with a utility module which offers many functions that are provided as a convenience to developers; it helps us avoid writing extra code for common tasks. The utility module is also used throughout the Node.js code base.

Here are several functions that check the data type of a value:

function isBoolean(arg) {
  return typeof arg === 'boolean';
}

function isNumber(arg) {
  return typeof arg === 'number';
}

function isString(arg) {
  return typeof arg === 'string';
}

function isFunction(arg) {
  return typeof arg === 'function';
}

The utility module gives a little more care when checking for an object:

function isObject(arg) {
  return arg !== null && typeof arg === 'object';
}

As the name suggests, the isObject function checks to see if a value is an object. But notice that isObject doesn't simply rely on checking that typeof returns "object" for arg. It first ensures that arg is not null. But why?

The answer is that null is a special case when it comes to the typeof operator:

> typeof null;

'object'

Applying the typeof operator to null returns "object". isObject doesn't consider null an object (nor do the majority of JavaScript programmers), so it ensures that arg is not null before checking to see if its type is "object".

(You may be asking yourself why does typeof return "object" when applied to null? Well, some consider it a mistake that has been a part of JavaScript for a long time. A proposal was submitted to fix this issue, but it was rejected in favor of backwards compatibility.)

In the following example, the isPrimitive function also explicitly tests for null. null is considered a primitive value. As a result, isPrimitive returns true if arg is null, or if it's not an object or function:

function isPrimitive(arg) {
  return arg === null || typeof arg !== 'object' &&
    typeof arg !== 'function';
}

Additional Uses and Examples of typeof

typeof is often used to test for the existence of a variable or function. If typeof is applied to a value that is not declared as a variable or function, it returns "undefined":

> typeof foo;

'undefined'

The DropzoneJS open source library uses typeof in this manner. DropzoneJS can work as a standalone library, but it can also work nicely along side the jQuery library. The following if-statement is found in the DropzoneJS source code; it checks to see if jQuery is available:

if (typeof jQuery !== 'undefined' && jQuery !== null) {
  // Add DropzonJS as jQuery plugin.
}

If jQuery is available, DropzoneJS is added to jQuery as a plugin.


Here is an excerpt from the jQuery source code that checks for the existence of a module system:

if (typeof module === 'object' &&
  typeof module.exports === 'object') {
  // Treat jQuery as a module.
} else {
  // Add jQuery to global environment.
}

If a module system exists, the jQuery library is treated as a module, otherwise it's exposed as a part of the JavaScript global environment. (We'll discuss modules in a later post — specifically Node.js modules.)

Bonus Tip

In an earlier example we saw that applying the typeof operator to an array returns "object".

> var numbers = [1, 2, 3, 4, 5];
> typeof numbers;

'object'

This isn't specific enough to be useful in most cases, as almost anything in JavaScript can be an object. In this simple example, it's clear that numbers is an array by looking at its definition. But in a real world project, we may not be able to track down where a variable is defined to get a sense of its data type.

In this scenario, if we have an idea of what kind of object a variable might (or should) be, we can use the instanceof operator:

> var numbers = [1, 2, 3, 4, 5];
> numbers instanceof Array;

true

instanceof of returns true because numbers is an Array object.

Additional Reading

In some scenarios, the instanceof operator can prove to be unreliable. But both typeof and instanceof are useful in most cases.

Read further about JavaScript data types and the typeof and instanceof operators via the Mozilla Developer Network: