Answer
In JavaScript, the typeof
operator is used to determine the type of a given value or variable. It returns a string indicating the type of the unevaluated operand. The typeof
operator can help in understanding and debugging your code by checking the data type of variables at runtime.
Here's the syntax for using the typeof
operator:
typeof operand
Or alternatively:
typeof(operand)
Both syntaxes work the same; the parentheses are optional.
Possible Return Values
The typeof
operator can return one of the following strings:
- "undefined": Indicates that the variable has not been assigned a value.
- "boolean": Indicates the value is a Boolean (
true
orfalse
). - "number": Indicates the value is a number, including
NaN
(which, paradoxically, stands for "Not a Number"). - "bigint": Indicates the value is a BigInt type, which can represent integers with arbitrary precision.
- "string": Indicates the value is a string.
- "symbol": Indicates the value is a Symbol, a unique and immutable primitive value.
- "object": Indicates the value is an object. It’s important to note that
null
also returns "object", which is considered a legacy bug in JavaScript. - "function": Indicates the value is a function. While technically functions are objects in JavaScript,
typeof
treats functions differently, allowing you to distinguish between objects and functions.
Examples
Here are some examples demonstrating the use of the typeof
operator:
console.log(typeof "Hello, world!"); // "string"
console.log(typeof 42); // "number"
console.log(typeof true); // "boolean"
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" (this is a known JavaScript quirk)
console.log(typeof {name: "Alice"}); // "object"
console.log(typeof [1, 2, 3]); // "object" (arrays are technically objects)
console.log(typeof function(){}); // "function"
console.log(typeof Symbol("id")); // "symbol"
console.log(typeof BigInt(123456)); // "bigint"
Usage Considerations
- The
typeof
operator is particularly useful when you need to ensure a certain type of data is being handled, or when debugging to check what type of data is in a variable. - However, it has limitations, especially with more complex data structures. For example, distinguishing between an array and an object requires more than just
typeof
since both return "object". - The unexpected result of
typeof null
being "object" is a well-known JavaScript oddity, stemming from a bug in the first implementation of JavaScript.