how to check if array contains an item javascript

How to Check if Array Contains an Item in JavaScript

If you are working with JavaScript, chances are that you will need to check if an array contains a specific item at some point. Fortunately, there are several ways to accomplish this task:

Method 1: Using the includes() Method

The easiest way to check if an array contains an item in JavaScript is to use the includes() method. This method returns true if the array contains the specified item, and false otherwise.


      const fruits = ['apple', 'banana', 'orange'];
      const hasApple = fruits.includes('apple');
      console.log(hasApple); // true
    

Method 2: Using the indexOf() Method

You can also use the indexOf() method to check if an array contains an item. This method returns the index of the specified item in the array, or -1 if the item is not found.


      const fruits = ['apple', 'banana', 'orange'];
      const hasApple = fruits.indexOf('apple') !== -1;
      console.log(hasApple); // true
    

Method 3: Using a for Loop

Another way to check if an array contains an item is to use a for loop to iterate over each element of the array.


      const fruits = ['apple', 'banana', 'orange'];
      let hasApple = false;
      
      for (let i = 0; i < fruits.length; i++) {
        if (fruits[i] === 'apple') {
          hasApple = true;
          break;
        }
      }
      
      console.log(hasApple); // true
    

These are three different ways to check if an array contains an item in JavaScript. Choose the method that works best for your specific use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe