What is the typeof operator in JavaScript?
Table of Contents
Introduction
The typeof
operator in JavaScript is used to determine the data type of a given variable or value. It is a unary operator, meaning it takes only one operand, and it returns a string indicating the type of the evaluated expression. This operator is extremely useful for debugging and type-checking.
Syntax of typeof
The syntax for using the typeof
operator is simple:
Here, operand
is the value or variable whose type you want to check.
Example:
How typeof
Works
The typeof
operator checks the data type of the operand and returns the type as a string. Below are some common data types and what typeof
will return for each:
1. Number
For numbers, whether integer or floating point, typeof
returns "number"
.
Example:
2. String
For strings, typeof
returns "string"
.
Example:
3. Boolean
For boolean values (true
or false
), typeof
returns "boolean"
.
Example:
4. Undefined
For variables that are declared but not assigned a value, typeof
returns "undefined"
.
Example:
5. Object
For objects, arrays, and null
, typeof
returns "object"
. However, keep in mind that there is a known quirk in JavaScript: typeof null
also returns "object"
.
Example:
6. Function
For functions, typeof
returns "function"
, making it easy to check if a variable is callable.
Example:
7. Symbol
For symbols, introduced in ES6, typeof
returns "symbol"
.
Example:
8. BigInt
For BigInt numbers, typeof
returns "bigint"
.
Example:
Common Use Cases of typeof
-
Type Checking: You can use
typeof
to ensure that a variable is of the correct type before performing an operation.Example:
-
Debugging: While debugging,
typeof
helps verify the type of variables and pinpoint issues.
Conclusion
The typeof
operator in JavaScript is a powerful tool for determining the type of a value or variable. It supports all basic data types such as numbers, strings, booleans, and even more complex types like functions and symbols. Understanding how typeof
works can help ensure that your code handles data correctly and effectively.