JavaScript Array includes() method


The includes() method in JavaScript is used to determine whether an array contains a specific element. It returns a boolean value: true if the element is found in the array, and false otherwise. This method is case-sensitive and can be particularly useful for checking membership in arrays.

Syntax:

let containsElement = array.includes(searchElement, fromIndex);
  • searchElement: The element to search for in the array.
  • fromIndex (optional): The index at which to begin the search. The default is 0. If the specified index is greater than or equal to the array's length, the search starts from the end of the array.

Return Value:

  • A boolean value (true or false):
    • true: If the specified element is found in the array.
    • false: If the specified element is not found.

Key Points:

  • Case-sensitive: The search is case-sensitive for string elements.
  • Searches the entire array by default: If fromIndex is not provided, the search starts from the beginning of the array.
  • Can find NaN: The includes() method can accurately determine if NaN is present in the array (unlike indexOf()).

Example 1: Basic usage (Checking for a number)

let numbers = [1, 2, 3, 4, 5]; let containsThree = numbers.includes(3); // Check if the array contains the number 3 console.log(containsThree); // true

Example 2: Searching with a starting index

let numbers = [1, 2, 3, 4, 5]; let containsFour = numbers.includes(4, 2); // Start searching from index 2 console.log(containsFour); // true

Example 3: Element not found

let fruits = ['apple', 'banana', 'orange']; let containsGrape = fruits.includes('grape'); // Look for an element that does not exist console.log(containsGrape); // false

Example 4: Searching for a string with case sensitivity

let words = ['hello', 'world', 'Hello']; let containsHello = words.includes('hello'); // Check for lowercase 'hello' let containsHelloCaps = words.includes('Hello'); // Check for uppercase 'Hello' console.log(containsHello); // false console.log(containsHelloCaps); // true

Example 5: Checking for NaN

let numbers = [1, 2, NaN, 4, 5]; let containsNaN = numbers.includes(NaN); // Check if NaN is in the array console.log(containsNaN); // true

Example 6: Using fromIndex to search from the end

let numbers = [1, 2, 3, 4, 5, 3]; let containsThreeFromIndex = numbers.includes(3, 4); // Start searching from index 4 console.log(containsThreeFromIndex); // false (the second occurrence is before index 4)

Summary:

  • The includes() method provides a simple way to check if an element exists within an array, returning true or false based on its presence.
  • This method is useful for membership tests, as it can accurately find NaN and respects case sensitivity for strings.
  • The optional fromIndex parameter allows for customized searching, including the ability to start searching from a specific index.