The typeof
operator is a fundamental tool in JavaScript for determining the data type of a value. Understanding how to use typeof
properly can help you write better code that is robust, debugged easily, and handles data types effectively. This comprehensive guide will explain everything you need to know about the JavaScript typeof
operator.
Introduction to the JavaScript typeof Operator
The typeof
operator in JavaScript returns a string representing the type of the operand it is provided. For example:
typeof "hello world"; // Returns "string"
This allows you to easily test the type of variables, function return values, objects, and more. Here are some key facts about the JavaScript typeof
operator:
- Returns a string indicating the type of the operand’s value
- Commonly used to test data before utilization
- Helps ensure values are valid and compatible
- Useful for debugging code and handling errors
- Case sensitive – must be written as
typeof
, notTypeof
- An operator, not a function – don’t use parentheses
- Unary operator – takes only one argument
Knowing the type of a value can prevent bugs and help you write code that handles data appropriately. The typeof
operator is your best tool for directly testing types in JavaScript.
The Possible Return Values of typeof
The typeof
operator can return one of the following string values:
- “undefined” – For undefined values
- “object” – For objects, arrays, and null
- “boolean” – For true or false
- “number” – For integers, floats, etc.
- “bigint” – For BigInt values
- “string” – For string primitives
- “symbol” – For symbol primitives
- “function” – For functions
It is important to note that typeof null
will return "object"
. This is a common source of confusion but is related to backwards compatibility.
Additionally, non-primitive object types like Dates and Regexes will also return "object"
. To distinguish between object subtypes, it is better to use Object.prototype.toString()
.
Now let’s look at some examples of using typeof
in JavaScript code.
Basic Examples of Using typeof in JavaScript
Here are some basic examples of how to use the typeof
operator in JavaScript:
// Numbers
typeof 37; // Returns "number"
typeof 3.14; // Returns "number"
typeof Math.LN2; // Returns "number"
typeof Infinity; // Returns "number"
typeof NaN; // Returns "number"
// Strings
typeof ""; // Returns "string"
typeof "bla"; // Returns "string"
typeof `template literal`; // Returns "string"
// Booleans
typeof true; // Returns "boolean"
typeof false; // Returns "boolean"
// Undefined
typeof undefined; // Returns "undefined"
typeof undeclaredVariable; // Returns "undefined"
// Objects/Arrays
typeof {}; // Returns "object"
typeof []; // Returns "object"
typeof null; // Returns "object"
// Functions
typeof function(){}; // Returns "function"
typeof Math.sin; // Returns "function"
As you can see, typeof
makes it straightforward to test the type of any value in JavaScript.
Now let’s go over some more complex examples of using typeof
.
More Examples of Using typeof in JavaScript
typeof
can be used in more advanced ways as well:
Comparing typeof to a String
You can compare the return value of typeof
to a string representing the type:
// Numbers
typeof 25 === "number"; // true
// Strings
typeof "hello" === "string"; // true
// Objects
typeof [1,2,3] === "object"; // true
This allows you to test if a value is a specific type.
Testing Function Parameters
You can use typeof
to validate the types of parameters passed to functions:
function add(x, y) {
if (typeof x !== "number") {
throw new Error("x must be a number");
}
if (typeof y !== "number") {
throw new Error("y must be a number");
}
return x + y;
}
This ensures the function is only called with the proper types.
Handling Different Types
You can use typeof
to handle values differently based on their type:
function print(val) {
if (typeof val === "number") {
console.log("The number is:", val);
} else if (typeof val === "string") {
console.log("The string is:", val);
} else {
throw new Error("Unsupport type");
}
}
This shows how typeof
allows you to write logic that can account for multiple types.
As you can see, typeof
can be leveraged in many useful ways when writing JavaScript code. Next we’ll cover some tips for using it effectively.
Tips for Using typeof Effectively
Here are some helpful tips for using the typeof
operator effectively:
Use typeof Regularly
Get in the habit of using typeof
often, especially when working with new or unfamilar code. This will prevent subtle bugs caused by incorrect types.
Put typeof Before Comparisons
When comparing types, always put typeof
before the comparison for readability:
// Clear
if (typeof x === "string") {
// ...
}
// Confusing
if ("string" === typeof x) {
// ...
}
Customize Error Messages
You can use typeof
to throw custom error messages based on data types:
if (typeof input !== "number") {
throw new Error("Input must be a number");
}
Label Arrays by Type
You can use typeof
to add type information when labeling array elements:
const people = [
{name: "John", type: "employee"}, // typeof "object"
25, // typeof "number"
true, // typeof "boolean"
];
This allows you to identify the type of each element.
Test Undeclared Variables
typeof
protects against ReferenceErrors when testing undeclared variables:
// This would throw an error if not wrapped in typeof
typeof someUnknownVariable === "undefined";
So typeof
is safer than directly accessing potentially undeclared variables.
By leveraging these tips and techniques, you can become an expert at using typeof
to write better JavaScript code. Next we’ll go over some alternatives to typeof
.
Alternatives to the JavaScript typeof Operator
While typeof
is the primary way to check types in JavaScript, there are some alternatives that can be useful in specific situations:
Object.prototype.toString()
This method returns a string representation of the object type:
Object.prototype.toString.call([1, 2, 3]); // "[object Array]"
Object.prototype.toString.call(new Date()); // "[object Date]"
This allows you to differentiate between object subtypes that typeof
considers just “object”.
.constructor
You can access an object’s constructor property to identify what it was constructed by:
[1, 2, 3].constructor; // Array()
(new Date()).constructor; // Date()
Again this allows you to differentiate objects with more granularity.
instanceof
The instanceof
operator tests if an object was constructed by a certain function:
[] instanceof Array; // true
{} instanceof Object; // true
new Date() instanceof Date; // true
So instanceof
provides a way to test object types.
In summary, while typeof
is the go-to for testing types in JavaScript, these alternatives can be used in special cases when needed.
Addressing Common Issues with typeof
While very useful, the typeof
operator does have some edge cases and common sources of confusion to be aware of. Here are some tips for addressing issues you may encounter:
typeof null Returns “object”
As mentioned earlier, this is just how JavaScript is defined and can’t be changed. Simply test for it explicitly:
value === null // true if null
Arrays and Objects Appear as “object”
Use Array.isArray()
or Object.prototype.toString()
to differentiate arrays and objects from each other.
Undeclared Variables Act Like “undefined”
Wrap in typeof
to prevent ReferenceErrors from undeclared variables.
Incorrect Return Values
Some edge cases like document.all may return unexpected results. Test and validate across browsers when in doubt.
Confusion with Complex Objects
Use .constructor
and instanceof
to differentiate objects with more granularity.
By being aware of these common pitfalls, you can avoid issues when using typeof
.
Conclusion
The typeof
operator is an invaluable tool for inspecting and handling data types in JavaScript. Here are some key takeaways:
- Use
typeof
to return a string indicating a value’s type - Common return values are “undefined”, “object”, “boolean”, “number”, “string”, etc
- Helps prevent bugs by testing values before use
- Allows handling values differently based on type
- More robust than direct type access or comparisons
- Some edge cases exist like typeof null being “object”
- Alternatives like
Object.prototype.toString()
can differentiate objects
Understanding typeof
is a fundamental JavaScript skill. Use this guide to leverage typeof
for writing better code that handles data types properly.The typeof
operator should be in every JavaScript developer’s toolbelt. Mastering its use will help you create robust code that avoids tricky type-related bugs.