How do you check the data type of a variable?
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
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 bug10typeof function () {}; // "function"
Checking for arrays
typeof returns "object" for arrays, so use Array.isArray():
1Array.isArray([]); // true2Array.isArray({}); // false3Array.isArray('hello'); // false
Checking for null
Since typeof null === "object", check for null explicitly:
1const value = null;2value === null; // true3typeof value === 'object' && value !== null; // false — it is null
instanceof
Checks if an object is an instance of a class:
1class Dog {}2const rex = new Dog();34rex instanceof Dog; // true5rex instanceof Object; // true — all objects inherit from Object67[] instanceof Array; // true8new 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:
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.