find(), findIndex() and includes() Array Methods in JavaScript

ยท

2 min read

find(), findIndex() and includes() Array Methods in JavaScript

Most of us find the element, or its index position by using the mannual method or by the mostly used built-in method called indexOf( ) in arrays, But some array methods are capable to find the element and its index position. Those methods are find( ), findIndex() and includes() (which returns true or false by depending of value, if it is present or not).

Let's go ๐Ÿš€ and discuss themโ€”โ€”โ€”-

Array.prototype.find()

The find() method takes the callback function and returns the value in the given array which satisfies the callback function condition. NOTE that ๐Ÿ“ข, it returns the value of the first element of the given array.

๐Ÿค”What callback function returns, if the no values satisfy the given callback function? Simple, It returns undefined.

let arr=[10,15,20,25,30]
arr.find(function(value){
  return value > 25;
});

//30
let arr=[10,15,20,25,30]
arr.find(function(value){
  return value < 25;
});

//10

Why is the above code returns 10? ๐Ÿ™„

As I already told you it returns the first matching value. In the callback function, it returns the value which is less than 25 ( value<25 ) and that is 10, which is the first matched value.


Array.prototype.findIndex()

The findIndex() method is the same as the find() method the only difference is it returns the index of the first element that satisfies the provided function condition.

If no element of the array satisfies the given condition of the callback function, it returns -1

let arr=[10,15,20,25,30]
arr.findIndex(function(value){
  return value > 25;    //here, 30 satisfies the condition which have 4th index
});

//4

Here, no value satisfies the given condition, so it returns -1 ๐Ÿ’โ€โ™‚๏ธ

let arr=[10,15,20,25,30]
arr.findIndex(function(value){
  return value > 35;
});

//-1

Array.prototype.includes()

The includes() method returns true or false according to value, whether the given array contained it or not

let arr=[10,15,20,25,30]
arr.includes(10);   //true
arr.includes(25);   //true
arr.includes(14);   //false

โžก๏ธ The includes() method also has the second optional parameter, which takes an index as the position of the array which determines from where the searching is to begin.

let arr=[10,15,20,25,30]
arr.includes(20,1);   //true
arr.includes(20,3);   //flase
ย