Trusted answers to developer questions

What is the Array.includes() method in JavaScript?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

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.

svg viewer

Syntax

svg viewer
  • array is the actual name of an array we want to search in.
  • element is the actual element we want to search for.
  • Start is an optional parameter. It is the index we want to start searching from. If we do not use this parameter, then the language, by default, starts searching from the 0th index.

Example 1:

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);

Example 2:

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.

RELATED TAGS

array
include
javascript
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?