Javascript Array - includes() Method

Tutorialsrack 09/10/2022 Jquery Javascript

In this article, you will learn about the javascript Array built-in method Array.prototype.includes(). How does this method work in javascript? 


This Array.prototype.includes() method checks whether the given array contains the specified element or not. It returns true if the array contains specific elements, otherwise, it returns false.

array.includes(searchElement, fromIndex);

This method takes 2 parameters as given below:

  • searchElement: This parameter holds the value to search for.
  • fromIndex(Optional):  This parameter holds the position in this array at which to begin searching for searchElement. And its defaults to 0

When you used Array.includes() method on sparse arrays, this method iterates empty slots as if they have the value undefined.

Here are some examples of Array.prototype.includes() method:

console.log([1, 2, 3].includes(2));
// Output => true

console.log([1, 2, 3].includes(4));         
// Output => false

console.log([1, 2, 3].includes(3, 3));      
// Output =>  false

console.log([1, 2, 3].includes(3, -1));     
// Output =>  true

console.log([1, 2, NaN].includes(NaN));     
// Output => true

console.log(["1", "2", "3"].includes(3));   
// Output => false

//fromIndex is greater than or equal to the array length
const arr = ['a', 'b', 'c', 'd'];

console.log(arr.includes('c', 3));    
// Output => false

console.log(arr.includes('c', 100));  
// Output => false

//Using includes() on sparse arrays
console.log([1, , 3, 4].includes(undefined)); 
//Output => true

I hope this article will help you to understand the javascript Array built-in method Array.prototype.includes()

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!

Related Posts


Recent Posts