How do you check the data type of a variable?
JavaScriptThe 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 bugtypeof function () {}; // "function"Checking for arrays
typeof returns "object" for arrays, so use Array.isArray():
Array.isArray([]); // trueArray.isArray({}); // falseArray.isArray('hello'); // falseChecking for null
Since typeof null === "object", check for null explicitly:
const value = null;value === null; // truetypeof value === 'object' && value !== null; // false — it is nullinstanceof
Checks if an object is an instance of a class:
class Dog {}const rex = new Dog();rex instanceof Dog; // truerex instanceof Object; // true — all objects inherit from Object[] instanceof Array; // truenew Date() instanceof Date; // trueinstanceof 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.