Javascript Array includes()

Introduction

Javascript Array includes() method check if an array contains a value.

It returns true or false.

arr.includes(valueToFind[, fromIndex])
  • valueToFind - The value to search for.
  • fromIndex - Optional, Defaults to 0. position to begin searching.

For negative fromIndex, it searches from arr.length + fromIndex.

Check if an array includes "Javascript":

var languages = ["CSS", "HTML", "Java", "Javascript"];
var n = languages.includes("Javascript");
console.log(n);//from   ww  w .  jav a2s  . com

Check if the array contains "CSS", when starting the search from position 3:

var languages = ["CSS", "HTML", "Java", "Javascript"];
var n = languages.includes("CSS", 3);

console.log(n);//from  www.  j a  v a2s  .  c om
let a = [1, 2, 3].includes(2);
console.log(a);      // true
a = [1, 2, 3].includes(4);//w  w  w  . jav a 2 s.  c om
console.log(a);// false
a = [1, 2, 3].includes(3, 3);
console.log(a);   // false
a = [1, 2, 3].includes(3, -1);
console.log(a);  // true
a = [1, 2, NaN].includes(NaN);
console.log(a);  // true

If fromIndex is greater than or equal to the length of the array, false is returned.

The array will not be searched.

let arr = ['a', 'b', 'c']

let a = arr.includes('c', 3);
console.log(a);    // false
a = arr.includes('c', 100);
console.log(a);  // false

If fromIndex is negative, it searches from arr.length + fromIndex.

If the computed index is less or equal than -(arr.length), the entire array will be searched.

let arr = ['a', 'b', 'c']

let a = arr.includes('a', -100);
console.log(a); // true
a = arr.includes('b', -100);
console.log(a); // true
a = arr.includes('c', -100);
console.log(a); // true
a = arr.includes('a', -2);
console.log(a);   // false

More example

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];

console.log(numbers.indexOf(4)); // 3 
console.log(numbers.lastIndexOf(4)); // 5 
console.log(numbers.includes(4)); // true 

console.log(numbers.indexOf(4, 4)); // 5 
console.log(numbers.lastIndexOf(4, 4)); // 3 
console.log(numbers.includes(4, 7)); // false 

let person = {//from   w w w.  j a va 2  s .  c  o  m
    name: "HTML"
};
let people = [{
    name: "HTML"
}];
let morePeople = [person];

console.log(people.indexOf(person)); // -1 
console.log(morePeople.indexOf(person)); // 0 
console.log(people.includes(person)); // false 
console.log(morePeople.includes(person)); // true 



PreviousNext

Related