Skip to content
the poor coder

includes with array in js

Poor Man
Published
Reading time
2 min read
On this page

Includes with Array in JavaScript#

If you are working with arrays in JavaScript, you might have come across a situation where you need to check whether an element exists in an array or not. This is where the includes() method comes in handy.

Using the includes() method#

The includes() method checks whether an element is present in an array or not and returns a boolean value. Here is an example:

Text

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

In the above example, we have an array of fruits and we are using the includes() method to check whether 'banana' and 'mango' are present in the array or not.

Using indexOf() method#

The indexOf() method can also be used to check whether an element exists in an array or not. The indexOf() method returns the index of the first occurrence of the specified element in the array. If the element is not present, it returns -1. Here is an example:

Text

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

In the above example, we are using the indexOf() method to check whether 'banana' and 'mango' are present in the array or not. We are comparing the returned index value with -1 to get a boolean result.

Using a for loop#

You can also use a for loop to check whether an element exists in an array or not. Here is an example:

Text

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

In the above example, we are using a for loop to iterate over the array and check whether 'banana' is present in the array or not. If it is present, we set the isPresent variable to true and break out of the loop.

So, these are some of the ways to check whether an element exists in an array or not in JavaScript.

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