DEV Community

Cover image for Check if an Item is in an Array in JavaScript – JS Contains with Array.includes()
Nwankwo  Samuel
Nwankwo Samuel

Posted on

Check if an Item is in an Array in JavaScript – JS Contains with Array.includes()

When working with JavaScript, you'll often encounter situations where you need to check if an item exists within an array. This is a common operation in programming and can be accomplished in various ways, but one of the most straightforward methods is by using the Array.includes() method. In this article, we'll explore how to use Array.includes() to determine whether an item is present in an array.

Understanding Array.includes()

Introduced in ECMAScript 2016 (ES7), the Array.includes() method provides a simple and elegant way to check if an element exists within an array. It returns a boolean value, true if the element is found, and false otherwise. The basic syntax is as follows:

array.includes(elementToFind[, startIndex])
Enter fullscreen mode Exit fullscreen mode
  • array: The array you want to search in.
  • elementToFind: The element you want to check for existence.
  • startIndex (optional): An optional parameter that specifies the position in the array to start the search. If omitted, the search starts from index 0.

Using Array.includes() to Check for Existence

Let's dive into some practical examples of how to use Array.includes():

Example 1: Checking for a Primitive Value

const numbers = [1, 2, 3, 4, 5];

const doesExist = numbers.includes(3);
console.log(doesExist); // true
Enter fullscreen mode Exit fullscreen mode

In this example, we have an array of numbers, and we use includes() to check if the number 3 exists in the array. The method returns true because 3 is indeed present in the array.

Example 2: Checking for an Object

const people = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 35 },
];

const personToFind = { name: 'Bob', age: 25 };

const doesExist = people.includes(personToFind);
console.log(doesExist); // false
Enter fullscreen mode Exit fullscreen mode

In this example, we have an array of objects representing people, and we want to check if a specific person object exists in the array. However, includes() returns false because object comparison is based on reference, and personToFind is a new object with a different reference.

Example 3: Using startIndex

const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

const doesExist = fruits.includes('cherry', 2);
console.log(doesExist); // true
Enter fullscreen mode Exit fullscreen mode

Here, we use the optional startIndex parameter to specify that the search should begin at index 2 in the array. As a result, includes() returns true because it finds 'cherry' starting from the specified index.

Compatibility and Polyfill

Array.includes() is a widely supported method in modern JavaScript environments. However, if you need to support older browsers or environments that don't have native support for Array.includes(), you can use a polyfill. A polyfill is a piece of code that provides the functionality of a newer JavaScript feature in older environments.

Here's a simple polyfill for Array.includes():

if (!Array.prototype.includes) {
  Array.prototype.includes = function (elementToFind, startIndex) {
    startIndex = startIndex || 0;

    for (let i = startIndex; i < this.length; i++) {
      if (this[i] === elementToFind) {
        return true;
      }
    }

    return false;
  };
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Checking if an item exists in an array is a fundamental operation in JavaScript, and Array.includes() simplifies this task by providing a concise and readable solution. Whether you're working with primitive values or objects, Array.includes() offers a versatile way to determine whether an element is present in an array. Just keep in mind that for object comparison, it checks references, so you may need to implement custom logic if you want to compare object properties.

By mastering Array.includes(), you'll be well-equipped to handle array searches efficiently in your JavaScript projects.

Happy coding!

Top comments (0)