Skip to content
the poor coder

Array Includes

Poor Man
Published
Reading time
1 min read
On this page

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:#

Text

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".

Text

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:

Text

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:

Text

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.

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