Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
include
javascript

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

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring