JavaScript provides two specific operators that help you identify what kind of data you are
working with: typeof and instanceof. These are essential for
writing safe code that handles different types of inputs correctly.
The typeof operator returns a string indicating the data type of an operand
(a variable or a literal).
| Example | Resulting Type |
|---|---|
typeof "Mim" |
"string" |
typeof 25 |
"number" |
typeof true |
"boolean" |
typeof {name:'Mim'} |
"object" |
typeof [1, 2, 3] |
"object" (Arrays are objects) |
typeof undefined |
"undefined" |
typeof function(){} |
"function" |
typeof null |
"object" (A known JS quirk) |
typeof null returns
"object". This is considered a mistake in the original JavaScript
implementation but has never been fixed to maintain compatibility with older websites.
The instanceof operator returns true if an object is an
instance of a specific object type (like a Class or a Constructor function).
const colors = ["Red", "Green", "Blue"];
const today = new Date();
console.log(colors instanceof Array); // true
console.log(today instanceof Date); // true
console.log(today instanceof Object); // true (everything is an object)
console.log(colors instanceof String); // false
Because JavaScript is a dynamically typed language, a variable can hold any type of value. Type operators help you verify data before performing operations.
function processInput(data) {
if (typeof data === "string") {
console.log("Processing text: " + data.toUpperCase());
} else if (typeof data === "number") {
console.log("Processing number: " + (data * 2));
}
}
typeof is used for primitive values like strings, numbers, and booleans
instanceof is used for objects like Arrays, Dates, and custom classestypeof null is "object" — keep this in mind when checking
for null values"object" when using typeof — use
Array.isArray() or instanceof to identify them correctly