Array Includes method in Javascript

    Apr 21, 2020       by Pankaj Kumar
javascript-array-includes.jpg

As we know, Javascript comes with a huge list of Array and String functions to perform operations on it. Javascript array includes() is also an inbuilt function that determines whether the current array contains an element or not, returning true or false as appropriate.

All the available modern browsers have array includes(), which does exactly that and is widely supported by everyone except Internet Explorer(IE).

Syntax

Following is the syntax for the Javascript array includes()

arr.includes(valueToFind[, fromIndex])

 

Parameters

valueToFind: The element needed to search

fromIndex: The position in the array at which search needed to begin for valueToFind.

 

Return value

includes() returns boolean, true is the search element is found inside the array and false if search element is not available inside the array.

 

Examples

 

[1, 2, 4].includes(2) // true

[1, 2, 4].includes(5) // false

[1, 2, 3].includes(3, 3) // false

[1, 2, 3].includes(3, -1) // true

[1, 2, NaN].includes(NaN) // true

 

fromIndex is greater than or equal to the array length

if fromIndex is greater than the array length, false is returned.

let arr = ['a', 'b', 'c']

arr.includes('c', 3) // false

arr.includes('c', 100) // false

 

includes() used as a generic method

includes() is intentionally generic. It does not need this value to be an Array object, so it can be applied to other kinds of objects (e.g. array-like objects).

The example below illustrates includes a () method called on the function's argument object.

(function() {

  console.log([].includes.call(arguments, 'a')) // true

  console.log([].includes.call(arguments, 'd')) // false

})('a','b','c')

 

Difference between Array.includes() and Array.indexOf()

The array includes() method was added with ECMAScript 6. This is used to find if the element is included in the array or not and return boolean true or false.

Array.indexOf() is used to find out if an element is present inside the provided array and if it is present than the index of the element inside the array is returned.

 

Conclusion

Working with includes() is very easy and it makes the search task on Array very easy.

 

Click here to find Sample Applications on different javascript frameworks.

Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.

Thank You!


WHAT'S NEW

Find other similar Articles here: