Curriculum Series

How do you check the data type of a variable?

How do you check the data type of a variable?

How do you check the data type of a variable?

JavaScript

The short answer

Use typeof for primitives, Array.isArray() for arrays, and instanceof for class instances. typeof has two well-known quirks: typeof null returns "object" and typeof function returns "function" (even though functions are technically objects).

typeof

JAVASCRIPT
1typeof 'hello'; // "string"
2typeof 42; // "number"
3typeof true; // "boolean"
4typeof undefined; // "undefined"
5typeof Symbol(); // "symbol"
6typeof 42n; // "bigint"
7typeof {}; // "object"
8typeof []; // "object" — arrays are objects!
9typeof null; // "object" — this is a bug
10typeof function () {}; // "function"

Checking for arrays

typeof returns "object" for arrays, so use Array.isArray():

JAVASCRIPT
1Array.isArray([]); // true
2Array.isArray({}); // false
3Array.isArray('hello'); // false

Checking for null

Since typeof null === "object", check for null explicitly:

JAVASCRIPT
1const value = null;
2value === null; // true
3typeof value === 'object' && value !== null; // false — it is null

instanceof

Checks if an object is an instance of a class:

JAVASCRIPT
1class Dog {}
2const rex = new Dog();
3
4rex instanceof Dog; // true
5rex instanceof Object; // true — all objects inherit from Object
6
7[] instanceof Array; // true
8new Date() instanceof Date; // true

instanceof checks the prototype chain, so it works with inheritance.

Object.prototype.toString (most reliable)

For a fully reliable type check:

JAVASCRIPT
1Object.prototype.toString.call(null); // "[object Null]"
2Object.prototype.toString.call([]); // "[object Array]"
3Object.prototype.toString.call({}); // "[object Object]"
4Object.prototype.toString.call(new Date()); // "[object Date]"
5Object.prototype.toString.call(/regex/); // "[object RegExp]"

This works for everything but is verbose. Use it when you need to distinguish between object types precisely.

Interview Tip

Start with typeof and its quirks (null returns "object", arrays return "object"). Then show Array.isArray and instanceof for more specific checks. Knowing about Object.prototype.toString as the nuclear option is a bonus.

Why interviewers ask this

This tests fundamental JavaScript knowledge about the type system. The typeof null bug and the need for Array.isArray come up in real code. Knowing these shows you understand JavaScript's type quirks.

Finished reading?

Mark this topic as solved to track your progress.