JavaScript Array includes() Method

JavaScript Array includes() method is used to check if an array contains the specified element.

Syntax

array.includes(element, fromIndex)

Parameters

  1. element(required):  It is the element that we need to search for.
  2. fromIndex(optional): It is the position in the array to start the search. (Default is 0)

Return Value

Returns true if element found, otherwise false.

Visual RepresentationVisual Representation of JavaScript Array includes() Method

Example 1: How to Use Array includes() Method

let nm = ["Elon", "Zuck", 'Jeff', 'Bill', 'Page']; 
console.log(nm.includes('Bill'));

Output

true

Example 2: Using the fromIndex parameterVisual Representation of Using the second parameter

let nm = ["Elon", "Zuck", 'Jeff', 'Bill', 'Page'];
console.log(nm.includes("Jeff", 1));
//passing negative index
console.log(nm.includes("Zuck", -2));

Output

truefalse

In the first use case, we have passed two arguments. it returns true because the value ‘Jeff ‘ is present in the array nm starting from the index 1.

In the second use case, we passed two arguments, the second argument being a negative index. Due to this negative index of -2, the method begins its search for ‘Zuck‘ starting from the second-last element of the array. As a result, it returns false.

Example 3: Element does not exist in the arrayVisual Representation of Element does not exist in the array

let nm = ["Elon", "Zuck", "Jeff", "Bill", "Page"];
console.log(nm.includes("Buffett"));

Output

false

Example 4:Case-Sensitive Search

When comparing strings and characters, the includes() function is case-sensitive.

let nm = ["Elon", "Zuck", "Jeff", "Bill", "Page"];
console.log(nm.includes("page"));
console.log(nm.includes("Page"));

Output

false
true

Difference between Array includes() and Array indexOf()

The Array includes() method checks if the element is included in the array. It returns the boolean value: true or false.

We use Array indexOf() to check whether the element is present in the array. But it doesn’t return a boolean. Instead, it returns the first index of the element found in the array or will return -1 (which represents that the element is not found).

Unlike array indexOf(), which uses Strict Equality Comparison, it includes comparisons using the SameValueZero equality algorithm. That means that you can detect if the array includes a NaN.

Browser compatibility

  • Google Chrome 47
  • Edge 14 
  • Firefox 43
  • Opera 34 
  • Safari 9 and above

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.