JavaScript Code

JavaScript Array includes()


includes() – Check if Element is in Array

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