Skip to content
the poor coder

how to check if array contains an item javascript

Poor Man
Published
Reading time
1 min read
On this page

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.

Text

      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.

Text

      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.

Text

      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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC