QA
Beginner LevelJavaScript & TypeScript

What is the typeof operator and how do you reliably check data types in JavaScript?

❓ Interview Prompt: Explain typeof returns, quirks (typeof null === "object"), and how Array.isArray(), instanceof, and Object.prototype.toString.call() work.

The typeof operator returns a string indicating the type of an unevaluated operand.

typeof Output Mapping:

•
number, string, boolean, undefined, symbol, bigint, function
•
Quirk: typeof null === 'object'
•
Quirk: typeof [] === 'object' (cannot distinguish Arrays from Objects)

Reliable Type Checking Techniques:

1
Arrays: Use Array.isArray(val).
2
Null: Use val === null.
3
Exact Type (Universal): Use Object.prototype.toString.call(val) (e.g. "[object Date]").
4
Class Instances: Use instanceof ClassName.

Code Implementation Example

javascript
// Universal reliable type checking helper
function getType(value) {
  if (value === null) return 'null';
  if (Array.isArray(value)) return 'array';
  return typeof value;
}

// Deep precise type checking via Object.prototype.toString
function getExactType(value) {
  return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}

console.log(getExactType(new Date()));    // "date"
console.log(getExactType(/regex/));       // "regexp"
console.log(getExactType(new Map()));     // "map"
console.log(getExactType(null));          // "null"
console.log(getExactType([1, 2, 3]));     // "array"
💡Overcoming typeof quirks using Object.prototype.toString.call and Array.isArray.
🎯 Interview Key Takeaway

Use Array.isArray() for arrays and Object.prototype.toString.call() for robust cross-frame type checking.

#Type Checking#typeof#Utility#Beginner
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?