ECMAScript question detail
Array Includes
Prior to ES7, you have to use indexOf method and compare the result with '-1' to check whether an array element contains particular element or not.
const array = [1,2,3,4,5,6];
if(array.indexOf(5) > -1 ){
console.log("Found an element");
}
Whereas in ES7, array.prototype.includes() method is introduced as a direct approach to determine whether an array includes a certain value among its entries or not.
const array = [1,2,3,4,5,6];
if(array.includes(5)){
console.log("Found an element");
}
In addition to this, Array.prototype.includes() handles NaN and Undefined values better than Array.prototype.indexOf() methods. i.e, If the array contains NaN and Undefined values then indexOf() does not return correct index while searching for NaN and Undefined.
let numbers = [1, 2, 3, 4, NaN, ,];
console.log(numbers.indexOf(NaN)); // -1
console.log(numbers.indexOf(undefined)); // -1
On the otherhand, includes method is able to find these elements
let numbers = [1, 2, 3, 4, NaN, ,];
console.log(numbers.includes(NaN)); // true
console.log(numbers.includes(undefined)); // true