How to use Array.prototype.findIndex() method In Javascript

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1.

const array = [1, 2, 3, 4, 5];
const element = 3;
// Checks if element exists
const exists = array.findIndex(item => item === element) !== -1;
console.log(exists); // Output: true

How to Check if an Element Exists in an Array in JavaScript ?

In JavaScript, you can check if an element exists in an array using various methods, such as indexOf(), includes(), find(), some(), or Array.prototype.findIndex().

Here’s how you can achieve it using these methods:

Table of Content

  • Using indexOf() method
  • Using includes() method
  • Using find() method
  • Using some() method
  • Using Array.prototype.findIndex() method

Similar Reads

Using indexOf() method

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present....

Using includes() method

The includes() method returns a boolean indicating whether an array includes a certain value among its entries....

Using find() method

The find() method returns the value of the first element in the array that satisfies the provided testing function....

Using some() method

The some() method tests whether at least one element in the array passes the test implemented by the provided function....

Using Array.prototype.findIndex() method

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1....