typeof Operator
Overview
The typeof operator is a handy tool to find out what data type a variable currently holds.
Because JavaScript is dynamically typed (a variable can be a string one moment and a number the next), you often need to check types before performing operations.
Syntax
typeof always returns a string representing the type.
console.log(typeof 42); // "number"
console.log(typeof "Hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof function(){}); // "function"This is a famous bug from the very first version of JavaScript. null is a primitive, but typeof says it's an object. For legacy compatibility reasons, it will never be fixed!
console.log(typeof null); // "object"Common Pitfalls
- Relying on
typeofto check for Arrays.typeof [1, 2, 3]returns"object". To properly check for an array, you must useArray.isArray(myVariable).
Interview Questions
It evaluates to 'object'. This is a historical bug in JavaScript's early implementation where the binary representation of null resulted in the engine misclassifying it as an object.
Real-World Example
When building an API endpoint, you must validate that the data the user sent is the correct type before saving it to a database.
function createUser(age) {
if (typeof age !== 'number') {
throw new Error("Age must be a number!");
}
// proceed to save...
}Check Your Knowledge
Test your understanding of typeof Operator with these quick questions.