The includes() method in JavaScript is used to check whether an array contains a specific value. It returns a boolean result, making element checks simple and readable.
- Returns true if the value exists, otherwise false
- Does not modify the original array
- Uses strict equality (===) for comparison
let numbers = [10, 20, 30, 40];
// Check if 20 is present in the array
let result = numbers.includes(20);
console.log(result);
Syntax
array.includes(searchElement, start);Parameters
- searchElement: This parameter holds the element that will be searched.
- start: This parameter is optional and it holds the starting point of the array, where to begin the search the default value is 0.
Return Value :It returns a Boolean value i.e., either True or False.
Example of JavaScript Array includes() Method
Here’s an example of the JavaScript Array.includes() method:
[Example 1]: Searching for a number in an array
In this example, the includes() method checks if the number 2 is present in the array A.
// Taking input as an array A
// having some elements.
let A = [1, 2, 3, 4, 5];
// includes() method is called to
// test whether the searching element
// is present in given array or not.
a = A.includes(2)
// Printing result of includes().
console.log(a);
[Example 2]: Searching for a string in an array
In this example, the includes() method checks if the string 'cat' is present in the array name. Since 'cat' is not in the array, it returns false.
// Taking input as an array A
// having some elements.
let name = ['gfg', 'cse', 'geeks', 'portal'];
// includes() method is called to
// test whether the searching element
// is present in given array or not.
a = name.includes('cat')
// Printing result of includes()
console.log(a);