The difference between typeof and instanceof in JavaScript is subtle but very important. Let’s break it down clearly:
1. typeof
- Purpose: Checks the data type of a variable or value.
- Returns: A string indicating the type.
- Syntax:
typeof value - Common returned values:
"undefined","boolean","number","string","bigint","symbol","function","object"- Example:
typeof 42; // "number"
typeof "hello"; // "string"
typeof true; // "boolean"
typeof {}; // "object"
typeof null; // "object" (quirky behavior)
typeof undefined; // "undefined"
typeof function(){}; // "function"- Notes:
- Works on primitives.
- Cannot tell object types apart (e.g., array vs object).
2. instanceof
- Purpose: Checks if an object is an instance of a constructor or class.
- Returns: A boolean (
trueorfalse). - Syntax:
object instanceof Constructor - Example:
const arr = [1, 2, 3];
arr instanceof Array; // true
arr instanceof Object; // true
arr instanceof String; // false
const date = new Date();
date instanceof Date; // true
date instanceof Object; // true- Notes:
- Works only on objects, not primitives.
- Checks prototype chain.
- Useful to distinguish between object types like
Array,Date,Map, etc.
Quick Comparison Table
| Feature | typeof | instanceof |
|---|---|---|
| Checks for | Data type (primitive) | Object type (constructor/class) |
| Returns | String | Boolean |
| Works on | Primitives & objects | Objects only |
| Example | typeof 123 // "number" | [1,2] instanceof Array // true |
✅ Rule of thumb:
- Use
typeoffor primitives (number,string,boolean, etc.) - Use
instanceoffor objects to check their class or constructor.
