Array.includes()
is just like a lot of other methods used in JavaScript (e.g. String.includes()
). Array.includes()
checks for a specific element’s presence in an array.
The method returns true or false, depending on the result. This proves that it is a boolean method.
Note: The Javascript
Array.includes()
method is case sensitive. Therefore, for an array of characters or strings, searching for ‘A’ is not the same as searching for 'a’.
Suppose you wanted to search for the value = 2 in an integer array. Following the diagram below may help you understand this concept.
This example, done without using the “start” parameter, searches for a number in an array. It is the same example used in the illustration above.
var myarray = [1, 3, 5, 2, 4];var check = myarray.includes(2);console.log(check);
This example uses the start parameter and shows how the element is missed if the parameter is over estimated.
var myarray = [1, 3, 5, 2, 4];var check = myarray.includes(3,2);if (check==true)console.log("Found");else{console.log("Not found");}
The code above searches for 3, starting the search from index 2. The search result will display “Not found” since 3 is placed on index 1. Try changing the index to 1, or 0, and it will find it correctly.