JavaScript typeof explained: How to check data types in JS
Photo: Charlie Solorzano/Pexels
Introduction
As a dynamically typed language, JavaScript variables can hold any data type, and the type can also change during runtime. While this flexibility allows developers to write concise and adaptable code, it can lead to unexpected bugs. Assuming incorrect data types can lead to runtime errors and faulty logic.
Thus, it becomes essential to implement type-checking in places where you are unsure about the variable data type. These checks are necessary for writing robust and error-free code.
One of the easiest ways to check the value type in JavaScript is by using the typeof
operator. This article will explore how typeof
works, its use cases, limitations, and best practices for effective type checking.
Understanding JavaScript data types
Learning about the different data types that JavaScript supports is crucial for selecting the correct type-checking method. You can refer to this article to learn about different data types available in JavaScript: JavaScript data types demystified: From primitives to objects.
typeof
operator
The typeof
operator is a built-in JavaScript operator that returns the type of a given value as a string. Its syntax is simple, and you can use typeof
with or without parentheses:
Examples
Limitations of typeof
typeof null
returnsobject
: This is a well-known quirk haunting the language from its early days. There is a lot of code depending on this quirk, so it is a hassle to remove it now.typeof []
returnsobject
:Array
is a specialized object, so it is not wrong, but it becomes difficult to differentiate between array and object usingtypeof.
To check the array type, useArray.isArray()
.
typeof
does not differentiate between different types of objects. We will learn about this in detail in another article.
When to use typeof operator - Use cases
Checking for undefined variables
Before accessing a variable that may not exist, you can use typeof
to prevent errors. For example, a check if the user exists or not:
Validating function parameters
Ensuring a function receives the correct type of input can prevent unexpected bugs.
Debugging and logging
When debugging, typeof
can help in quickly identify data types. Thus allowing you to identify bugs related to types.
Summary
In this article, we have learned how to perform type-checking using the typeof
operator. We have also looked into its limitations and how it is helpful in real-world scenarios. Despite its limitations, we can always use it effectively for primitive types. We will learn how to check object types in another article.