JavaScript Code


JavaScript Array includes()


Check if Element is in Array in JavaScript

In JavaScript, Array.includes() method is used to check if a specific element is present in the array.

Syntax

array.includes(element)
array.includes(element, start)
  • array is an array of elements.
  • includes is the array method name.
  • element is the element to check if present in the array.
  • start is an integer, optional value. default value is 0.

includes() method returns true if the element is present in the array, or returns false otherwise. If start is passed as argument to includes(), then the search for the element starts from this index.

Examples

1. Check if the element 'cherry' is present in the array fruits.

let fruits = ['apple', 'banana', 'cherry'];
let element = 'cherry';
let isElementPresent = fruits.includes(element);
console.log('Is cherry present in fruits? ' + isElementPresent);

2. Check if the element 'apple' is present in the array fruits, from a start index of 1.

let fruits = ['apple', 'banana', 'cherry'];
let element = 'apple';
let start = 1;
let isElementPresent = fruits.includes(element, start);
console.log('Is apple present in fruits from index 1? ' + isElementPresent);

Since the index of element 'apple' is 0, and we are checking from the index of 1, includes() returns false.


Copyright @2022