Array.includes()

The Array.includes() method in JavaScript is used to determine if an array contains a specified element. It returns true if the element is found, and false otherwise.

Syntax

</>
Copy
includes(searchElement)
includes(searchElement, fromIndex)

Parameters

ParameterDescription
searchElementThe element to search for in the array.
fromIndexOptional. The position in the array at which to begin the search. The default is 0. If the value is negative, the search starts from the end of the array.

Return Value

The includes() method returns true if the specified element is found in the array, otherwise it returns false.


Examples

1. Checking for an Element in an Array

This example demonstrates how to check if an array contains a specified element.

</>
Copy
const fruits = ["apple", "banana", "cherry"];

console.log(fruits.includes("banana"));
console.log(fruits.includes("grape"));

Output

true
false
  1. fruits.includes("banana") returns true because “banana” is in the fruits array.
  2. fruits.includes("grape") returns false because “grape” is not in the fruits array.

2. Using fromIndex Parameter

The fromIndex parameter specifies the position in the array at which to start the search.

</>
Copy
const numbers = [1, 2, 3, 4, 5, 6];

console.log(numbers.includes(3, 2));
console.log(numbers.includes(3, 4));

Output

true
false
  1. numbers.includes(3, 2) returns true because the search starts at index 2, where the element 3 is located.
  2. numbers.includes(3, 4) returns false because the search starts at index 4, and the element 3 is not found beyond this index.

3. Case Sensitivity in includes()

The includes() method is case-sensitive, meaning it differentiates between uppercase and lowercase characters.

</>
Copy
const letters = ["A", "B", "C"];

console.log(letters.includes("a"));
console.log(letters.includes("A"));

Output

false
true
  1. letters.includes("a") returns false because “a” (lowercase) is not the same as “A” (uppercase).
  2. letters.includes("A") returns true because “A” (uppercase) is in the letters array.

4. Using includes() with Negative fromIndex

A negative fromIndex value is interpreted as an offset from the end of the array.

</>
Copy
const colors = ["red", "green", "blue", "yellow"];

console.log(colors.includes("green", -3));
console.log(colors.includes("red", -2));

Output

true
false
  1. colors.includes("green", -3) returns true because the search starts three elements from the end, where “green” is located.
  2. colors.includes("red", -2) returns false because “red” is not found when starting the search from two elements from the end.