JavaScript typeof Operator
The `typeof` operator in JavaScript is used to determine the type of a given value. It is a unary operator that returns a string indicating the type of the unevaluated operand.
1. Syntax
The syntax for the `typeof` operator is:
typeof operand
Where `operand` is the value whose type you want to determine.
2. Return Values
The `typeof` operator returns one of the following strings:
- "undefined" - If the value is `undefined`.
- "boolean" - If the value is a boolean (`true` or `false`).
- "number" - If the value is a number (including `NaN` and `Infinity`).
- "string" - If the value is a string.
- "object" - If the value is an object (including `null`, arrays, and dates).
- "function" - If the value is a function.
- "symbol" - If the value is a symbol (introduced in ES6).
3. Examples
Here are some examples of how `typeof` can be used:
// Examples using typeof
console.log(typeof undefined); // Output: "undefined"
console.log(typeof true); // Output: "boolean"
console.log(typeof 42); // Output: "number"
console.log(typeof 'Hello'); // Output: "string"
console.log(typeof { name: 'John' }); // Output: "object"
console.log(typeof [1, 2, 3]); // Output: "object" (arrays are objects)
console.log(typeof new Date()); // Output: "object" (dates are objects)
console.log(typeof function() {}); // Output: "function"
console.log(typeof Symbol('sym')); // Output: "symbol"
4. Special Cases
There are a few special cases to be aware of:
- Null Values: `typeof null` returns `"object"`. This is considered a historical bug in JavaScript.
- Arrays: `typeof` arrays returns `"object"`. To specifically check if a value is an array, use `Array.isArray()`.
- Functions: `typeof` functions returns `"function"`. Functions are a special type of object.
5. Common Pitfalls
Be cautious of the following pitfalls:
- Type of null: As mentioned, `typeof null` returns `"object"`, which can be misleading. Use `=== null` to explicitly check for null values.
- Arrays as Objects: Since arrays are objects, `typeof` won't differentiate them from plain objects. Use `Array.isArray()` for arrays.
- Functions: Functions are treated as a type of object, so `typeof` can be misleading if you are expecting to check types other than functions.