JavaScript typeof
Operator: A Complete Guide
JavaScript is a dynamically-typed language, which means that the data types of variables are determined automatically at runtime. However, sometimes it can be useful to know the data type of a particular value or variable. This is where the typeof
operator comes in.
In this article, we’ll take a comprehensive look at the typeof
operator in JavaScript, including what it is, how it works, and some practical examples of how it can be used.
What is the typeof
operator?
The typeof
operator is a built-in JavaScript operator that returns a string indicating the type of the operand. It takes a single argument and returns a string representing the data type of that argument. The syntax for using typeof
is as follows:
typeof operand
The operand
can be any expression or variable name. The return value is a string that can be one of the following:
"undefined"
: If the operand isundefined
."boolean"
: If the operand is a Boolean value (true
orfalse
)."number"
: If the operand is a number."bigint"
: If the operand is a BigInt."string"
: If the operand is a string."symbol"
: If the operand is a symbol."function"
: If the operand is a function."object"
: If the operand is an object (including arrays, null, and objects created withObject()
ornew Object()
)."null"
: If the operand isnull
.
Let’s look at some examples to understand the typeof
operator better.
Examples
Example 1: typeof
with primitive types
typeof undefined; // "undefined"
typeof true; // "boolean"
typeof 42; // "number"
typeof "hello"; // "string"
typeof Symbol(); // "symbol"
Example 2: typeof
with functions
typeof function(){}; // "function"
typeof class {}; // "function"
Example 3: typeof
with objects
typeof {}; // "object"
typeof []; // "object"
typeof null; // "object"
typeof new Object(); // "object"
In the third example above, it may be surprising that typeof null
returns "object"
. This is because null
is actually an empty object reference.
Common Use Cases
The typeof
operator is a useful tool in a number of scenarios. Here are some common use cases:
1. Checking if a variable is defined
if (typeof someVariable !== "undefined") {
// someVariable is defined
} else {
// someVariable is undefined
}
2. Checking the data type of a variable
if (typeof someVariable === "number") {
// someVariable is a number
}
3. Handling null values
function doSomething(arg) {
if (typeof arg === "object" && arg !== null) {
// arg is an object (excluding null)
}
}
4. Checking if a value is a function
if (typeof someValue === "function") {
// someValue is a function
}
The typeof
operator is a powerful tool in JavaScript that can help you determine the data type of a variable or value. It’s especially useful when working with dynamic data types or when handling values that may be null
or undefined
.