How to Check if an Array Includes a Value in JavaScript
Photo: Andres Ayrton/Pexels
Introduction
In this article, we will learn about the includes()
method in JavaScript,
which helps us determine whether an array contains a specific value.
It's like playing hide-and-seek with data—you have a value and need to check if it's hiding
somewhere in the array.
Table of Contents
- The includes() method
- Syntax: includes() method
- Starting search from a particular index
- Case Sensitivity and Type Checking
- Some use-cases of includes() method
The includes() method
Let's consider a real-world example to understand the includes()
method better.
Imagine you are hosting a party. You have a guest list with the names of all the
people you have invited. When someone arrives at the door, you must quickly check
if their name is on the list. We will use the includes()
method for the above example
and write a simple solution for the above scenario.
When a person from the guestList arrives at the door, the includes()
method returns
true or otherwise false.
Syntax: includes() method
- valueToFind: The value you want to check for in the array.
- fromIndex(optional): This is the index from where you start looking for the value in the array.
Starting search from a particular index
You might want to start checking from a specific point in the array, not always from the beginning. This is where fromIndex comes in handy. Consider you're only interested in the latter half of your language list:
Case Sensitivity and Type Checking
Remember, includes() is case-sensitive and type-specific. It won't find ' JavaScript ' if you're looking for 'javascript'. Similarly, you'll get different results if you check for a number as a string (like '5') versus a number (like 5).
Some use-cases of includes() method
- Form Validation: Ensure that user input matches a list of valid options.
- Filtering Data: Quickly identify items in an array that meet certain criteria.
- Checking Permissions: Verify if a user has a specific role or access level.
- Search Functionality: Determine if a search term is present within a dataset.