The includes() method of the Array class in JavaScript determines whether the calling array contains a specified value, returning true or false as appropriate.
There are 2 variations for the syntax of Array.includes() method. They are:
includes(searchElement)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchElement | required | The value to search for in the array. |
This method determines whether the calling array contains the specified value, starting the search at the beginning of the array.
Returns value of type Boolean
.
includes(searchElement, fromIndex)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
searchElement | required | The value to search for in the array. |
fromIndex | optional | The position in the array at which to begin the search. Defaults to 0. |
This method determines whether the calling array contains the specified value, starting the search at the specified fromIndex.
Returns value of type Boolean
.
In JavaScript, we can use the includes() method to check if an array contains a specified value.
For example,
const arr = [1, 2, 3, 4, 5];
const containsThree = arr.includes(3);
console.log(containsThree);
true
We can use the includes() method to check if an array contains a specified value, starting the search from a specific index.
For example,
const arr = [1, 2, 3, 4, 5];
const containsThreeFromIndex3 = arr.includes(3, 3);
console.log(containsThreeFromIndex3);
false
We can use the includes() method to check if an array contains a specified string value.
For example,
const strArr = ['apple', 'banana', 'cherry'];
const containsBanana = strArr.includes('banana');
console.log(containsBanana);
true
In this JavaScript tutorial, we learned about includes() method of Array: the syntax and few working examples with output and detailed explanation for each example.