Array Includes

Array Includes

Array includes is a method in JavaScript that allows us to check if an array includes a certain element or not. This method returns a boolean value (true or false). It helps us to avoid using loops to find an item in an array.

Syntax:


array.includes(value)
  • array: The array in which we want to check for the element.
  • value: The element we want to check for in the array.

Example:

Let's create an array of fruits and check if it includes "banana".


const fruits = ['apple', 'banana', 'mango', 'orange'];
const hasBanana = fruits.includes('banana');

console.log(hasBanana); // true

As you can see, the includes() method returns true because the array contains "banana".

Multiple Ways:

There are multiple ways to check if an array includes an element or not. One way is to use the indexOf() method. The other way is to use a for loop.

1. Using indexOf() method:


const fruits = ['apple', 'banana', 'mango', 'orange'];
const hasBanana = fruits.indexOf('banana') !== -1;

console.log(hasBanana); // true

The indexOf() method returns -1 when the element is not found in the array. So, we check if the returned value is not -1 to get a boolean result.

2. Using for loop:


const fruits = ['apple', 'banana', 'mango', 'orange'];
let hasBanana = false;

for(let i = 0; i < fruits.length; i++){
  if(fruits[i] === 'banana'){
    hasBanana = true;
    break;
  }
}

console.log(hasBanana); // true

We iterate through the array using a for loop and check if each element is equal to the required element. If found, we set the boolean variable to true and break out of the loop.

Out of all these methods, includes() is the most efficient and easiest way to check if an array includes an element or not.

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