The typeof operator in JavaScript is used to determine the type of a given operand. It returns a string indicating the type of the operand’s value.
Syntax
typeof operand
- operand: The value or expression whose type you want to determine.
Types Returned by typeof
The typeof operator returns one of the following strings:
"undefined": If the value isundefined."object": If the value isnullor an object (arrays, dates, objects, etc.)."boolean": If the value is a boolean (trueorfalse)."number": If the value is a number (includingNaN)."bigint": If the value is a BigInt."string": If the value is a string."symbol": If the value is a symbol."function": If the value is a function.
Examples
1. Checking Basic Data Types:
console.log(typeof 42); // Output: "number"
console.log(typeof 'hello'); // Output: "string"
console.log(typeof true); // Output: "boolean"
console.log(typeof undefined); // Output: "undefined"
console.log(typeof Symbol()); // Output: "symbol"
console.log(typeof BigInt(123)); // Output: "bigint"
console.log(typeof null); // Output: "object" (historical quirk)
console.log(typeof {}); // Output: "object"
console.log(typeof []); // Output: "object"
console.log(typeof function(){}); // Output: "function"
2. Checking Variables:
let x; console.log(typeof x); // Output: "undefined" x = 42; console.log(typeof x); // Output: "number" x = 'hello'; console.log(typeof x); // Output: "string" x = null; console.log(typeof x); // Output: "object"
3. Using typeof in Conditional Statements:
function checkType(value) {
if (typeof value === 'string') {
console.log('It is a string!');
} else if (typeof value === 'number') {
console.log('It is a number!');
} else {
console.log('It is some other type!');
}
}
checkType('hello'); // Output: It is a string!
checkType(42); // Output: It is a number!
checkType(true); // Output: It is some other type!
Special Cases
nullReturns"object":- This is a known issue in JavaScript for historical reasons. Use strict comparison to check for
null.let x = null; console.log(typeof x); // Output: "object" console.log(x === null); // Output: true
- This is a known issue in JavaScript for historical reasons. Use strict comparison to check for
NaNis of Type"number":- Although
NaNstands for “Not-A-Number”, its type is"number".console.log(typeof NaN); // Output: "number"
- Although
Conclusion
The typeof operator is a handy tool for identifying the type of a variable or value in JavaScript.