JavaScript typeof Operator
The `typeof` operator returns a string describing the type of a value, such as 'string', 'number', 'boolean', 'object', 'function', or 'undefined'.
It's frequently used to check argument types, guard against errors, or debug unexpected values, despite a few well-known quirks.
Common results
`typeof 'x'` is 'string', `typeof 42` is 'number', `typeof true` is 'boolean', `typeof undefined` is 'undefined', and `typeof function(){}` is 'function'.
Quirks
`typeof null` returns 'object' (a long-standing bug kept for compatibility), and `typeof NaN` returns 'number' since NaN is technically a numeric type.
console.log(typeof "hi");
console.log(typeof function() {});
console.log(typeof null);string
function
objectFunctions report as 'function', while null oddly reports as 'object'.
let x;
console.log(typeof x);undefinedAn unassigned variable has the value and type undefined.
Key points
- typeof returns a string naming a value's type.
- typeof null is 'object' โ a historical quirk.
- typeof of a function is 'function', not 'object'.
- typeof is useful for basic runtime type checks.
