JavaScript typeof Operator
By Flavio Copes
Learn how the JavaScript typeof operator returns a string for any value, from number and string to object and function, and how to detect undefined.
The typeof operator returns a string that tells you the type of a value. In JavaScript, any value has a type assigned, and typeof is how you inspect it at runtime.
It’s a unary operator, meaning it takes a single operand:
typeof 1 //'number'
typeof '1' //'string'
typeof {name: 'Flavio'} //'object'
typeof [1, 2, 3] //'object'
typeof true //'boolean'
typeof undefined //'undefined'
typeof (() => {}) //'function'
typeof Symbol() //'symbol'
typeof 10n //'bigint'
You typically reach for it when a value could be one of several types. A function parameter that accepts a string or a number, an options object that may or may not exist, that kind of situation.
The quirks you should know
JavaScript has no “function” type, and it seems funny that typeof returns 'function' when we pass it a function. It’s one quirk of it, to make our job easier.
Notice also that arrays report 'object'. There is no 'array' result. To detect an array, use Array.isArray() instead:
Array.isArray([1, 2, 3]) //true
The biggest quirk is null:
typeof null //'object'
This is a historical bug from the very first version of JavaScript, kept for backward compatibility. It means typeof alone can’t tell a real object from null. If you get 'object', check for null explicitly:
if (value !== null && typeof value === 'object') {
//it's really an object
}
How to check for undefined
If you don’t initialize a variable when you declare it, it holds the undefined value until you assign one:
let a //typeof a === 'undefined'
typeof also works on object properties. If you have a car object with just one property:
const car = {
model: 'Fiesta'
}
This is how you check if the color property is defined:
if (typeof car.color === 'undefined') {
//color is undefined
}
One more useful detail: typeof is the only operator that doesn’t throw when you pass it a variable that was never declared:
typeof somethingNeverDeclared //'undefined'
Any other access to that name would raise a ReferenceError. This makes typeof handy to check if a global exists, like typeof window === 'undefined' to detect if code is running outside the browser.
Related posts about js: