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

typeof 'hello'; // "string"
typeof 42; // "number"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof Symbol(); // "symbol"
typeof 42n; // "bigint"
typeof {}; // "object"
typeof []; // "object" — arrays are objects!
typeof null; // "object" — this is a bug
typeof function () {}; // "function"

Checking for arrays

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

Array.isArray([]); // true
Array.isArray({}); // false
Array.isArray('hello'); // false

Checking for null

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

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

instanceof

Checks if an object is an instance of a class:

class Dog {}
const rex = new Dog();
rex instanceof Dog; // true
rex instanceof Object; // true — all objects inherit from Object
[] instanceof Array; // true
new 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:

Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call(new Date()); // "[object Date]"
Object.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.