JavaScript typeof Operator
Last Updated : 13 Dec, 2024
Improve
The typeof operator in JavaScript is used to determine the data type of a value or variable. It returns a string indicating the type, such as "string", "number", "boolean", "object", etc.
console.log(typeof "Hello");
console.log(typeof 42);
console.log(typeof true);
console.log(typeof {});
console.log(typeof undefined);
Output
string number boolean object undefined
Key Points:
- Always outputs the data type as a string.
- Can be used anywhere without imports or dependencies.
- Determines the type of literals, variables, and expressions.
- Special Cases:
- typeof null returns "object" (a known quirk).
- Functions return "function" instead of "object".
- Useful for checking types in dynamic or untyped environments.
Syntax:
typeof operand
- operand: The value or variable to check.
Real-World Examples
Example 1: Validating User Input
function fun(input) {
if (typeof input === "number") {
console.log("Valid number provided!");
} else {
console.log("Please provide a number.");
}
}
fun(42);
fun("Hi");
Output
Valid number provided! Please provide a number.
Example 2: Dynamic Property Access
const settings = { darkMode: true };
if (typeof settings.darkMode === "boolean") {
console.log("Dark mode setting is valid.");
}
Output
Dark mode setting is valid.
Primitive Data Types
Primitive data types in JavaScript are basic data types that represent single values. They include:
Data Type | Description |
---|---|
Number | Represents numeric values like integers and floating-point numbers. |
String | Represents textual data enclosed within single quotes ('') or double quotes (""). |
Boolean | Represents true or false values. |
Undefined | Represents a variable that has been declared but has not been assigned a value. |
Null | Represents the intentional absence of any object value. |
Symbol | Represents a unique and immutable data type used as the key of an object's property. |
BigInt | Represents large integers beyond the limit of the Number type. |
Limitations
- typeof null returns "object", which is misleading and a legacy bug in JavaScript.
- Cannot distinguish between arrays and objects (typeof [] is "object").
- Cannot differentiate between classes or specific object types.
- typeof NaN returns "number", though it's technically "not a number."