JavaScript typeof
8 April 2025 | Category: JavaScript
The typeof
operator in JavaScript is used to check the data type of a variable or value. It returns a string indicating the type.
â Syntax:
typeof operand
OR
typeof(operand)
đ˘ Common Examples
typeof "Hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof { name: "Ali" } // "object"
typeof [1, 2, 3] // "object"
typeof null // "object" â (known quirk)
typeof function() {} // "function"
đ typeof
Results Table
Value | typeof Result |
---|---|
"Hello" | "string" |
123 | "number" |
true / false | "boolean" |
undefined | "undefined" |
{} (object literal) | "object" |
[] (array) | "object" |
null | "object" â |
function() {} | "function" |
Symbol("id") | "symbol" |
BigInt(1234567890123456789) | "bigint" |
â ď¸ Important Notes
1. â typeof null
returns "object"
This is a known bug in JavaScript that exists for backward compatibility.
typeof null; // "object" (even though it's null)
You can check for null more reliably using:
value === null
2. Arrays return "object"
Even though arrays are different from plain objects:
typeof [1, 2, 3]; // "object"
To specifically check for arrays, use:
Array.isArray([1, 2, 3]); // true
đ Checking Multiple Types
You can use typeof
inside conditionals:
function checkType(val) {
if (typeof val === "string") {
console.log("This is a string.");
} else if (typeof val === "number") {
console.log("This is a number.");
} else {
console.log("Unknown type.");
}
}
đ§Ş Real-world Example
const inputs = [42, "hello", true, null, undefined, [1, 2], {}, () => {}];
inputs.forEach(item => {
console.log(`${item} => ${typeof item}`);
});
â Summary
typeof
returns a string indicating the type of a value.- Useful for debugging and type checking.
- Be aware of quirks like:
typeof null
â"object"
typeof array
â"object"