javascript includes method

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

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

We already have indexOf() method which checks the value contains 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 additional validation 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

Javascript array contains an element Using Es6 syntax

In ES6,using indexOf() method always return integer or -1. Developer needs to write a code to check integer value is not equal -1 or not. The functionality works but readability is not good.

Here is an code for javascript array contains example

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 

Javascript includes example

This method introduced in native array and replace the usage of indexOf method natively.

This method returns Boolean value, which 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');

Difference between Includes with IndexOf method in javascript

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

Here is an example for comparing index and includes method

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

Points to remember

  • Both will behave same for array contains checking in javascript and works as expected
  • If array contains NaN values It returns true in case of includes as expected. IndexOf returns -1 which is not expected.
  • Checking Null or undefined contains in javascript returns as expected in case of indexOf and Includes method