The typeof Operator
typeof tells you the type of a value.
Syntax
typeof valueThe typeof operator returns a string describing the type of a value. It is useful for checking what you are working with.
Common results
typeof 'hi'→'string'typeof 42→'number'typeof true→'boolean'typeof undefined→'undefined'
Example
Loading editor…
Press Run to execute the code.
When to use it
- Guard a function that expects a string by checking typeof input === "string" before processing.
- Detect whether an optional callback argument was actually passed before calling it.
- Determine at runtime whether an external API response field is a number or a stringified number.
More examples
Basic typeof on primitives
Shows typeof results for the four most common primitive types.
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"Guard an optional callback
Uses typeof to safely check whether a callback was provided before invoking it.
function runTask(callback) {
const result = "done";
if (typeof callback === "function") {
callback(result);
}
}
runTask(console.log); // "done"
runTask(); // no errortypeof null quirk
Highlights the well-known quirk where typeof null returns "object", and shows the correct way to test for null.
console.log(typeof null); // "object" – historical bug in JS
console.log(null === null); // true – use strict equality for null check
Discussion