JavaScript Array includes() Method
JavaScript Array includes() method that checks if an array contains a specific element. It returns true if the element is found, and false otherwise. It’s useful for determining the presence of elements without needing to loop through the array.
Array includes() Method Syntax
array.includes(searchElement, start);
Array includes() Method 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.
Array includes() Method Return Value
It returns a Boolean value i.e., either True or False.
Array includes() Method Examples
Example 1: Searching for number in an array
Here, the method will search for element 2 in that array.
javascript
let A = [1, 2, 3, 4, 5];
a = A.includes(2)
console.log(a);
|
Explanation
This code demonstrates the use of the includes()
method to check if the element ‘2’ is present in the array A
. The method returns true
because ‘2’ is found in the array.
Example 2: Searching for a string in an array
Here, the method will search for the element ‘cat’ in that array and returns false as ‘cat’ is not present in the array.
javascript
let name = [ 'gfg' , 'cse' , 'geeks' , 'portal' ];
a = name.includes( 'cat' )
console.log(a);
|
Explanation
This code demonstrates the use of the includes()
method to check if a specific element (‘cat’) is present in the array name
. The method returns false
because ‘cat’ is not found in the array.
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete referencearticle.
Supported Browsers:
Last Updated :
05 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...