ES7 Array includes

This tutorial covers new method includes introduced in Array classs of ES7, ES2016 javascript..

new method includes

ES7 also called as ES7 is the latest javascript language released in 2017.

es7 introduced one method to Array.prototype.includes, incldues method in array is to check object or element exists in array.

We already have indexOf() method which checks the value exists in an array and returns the position in an array if found,if not returns -1. This always returns integer not boolean value. We have to write addtional validatoin check to make its truthy/falsy values.

includes syntax

array.includes(element[, fromIndex]) 

element is a value to check in array fromIndex is optional which starts from position to search which is useful for improve in performance.

It returns true if element found, else not found

Check element Using Es6 syntax

using indexOf() method, We have to check always with integer value of not equal -1. The functionality works but readability is not good.

let ecmaScriptArray = ['es6', 'es7', 'es7']

// Valid
if (ecmaScriptArray.indexOf('es7') !== -1) {
  console.log('Found an element');
}
// invalid
if (ecmaScriptArray.indexOf('es71')) {
    console.log('Execution will not print this');
}
ecmaScriptArray.indexOf('es71') returns -1 
ecmaScriptArray.indexOf('es7') returns 0 

example for includes

With includes method in array, It is replacing indexOf method. This method returns boolean value, can be used in conditional expression without extra step for checking for boolean type.

let ecmaScriptArray = ['es6', 'es7', 'es7']

// Correct
if (ecmaScriptArray.includes('es7')) {
    console.log('Found an element');
}

Compare Includes method with IndexOf method

Includes method handles NAN( not an number) as expected compared with indexOf method Null are not allowed in both methods.

console.log(["one", "two", "three"].includes("one")); // true
console.log(["one", "two", "three"].includes("five")); // false
console.log([5, NaN, 4].includes(NaN)) //true
console.log([5, undefined, 4].includes(undefined)) // true
    //console.log([5, Null, 4].includes(Null)) // compilation error, null not allowed

console.log(["one", "two", "three"].indexOf("one")); // 0
console.log(["one", "two", "three"].indexOf("five")); //-1
console.log([5, undefined, 4].indexOf(undefined)) // 1
    //console.log([5, Null, 4].indexOf(Null)) // compilation error, null not allowed
console.log([5, NaN, 4].indexOf(NaN)) // -1
Prev Next