Includes() vs indexOf() in JavaScript

April 27, 2018 0 Comments

Includes() vs indexOf() in JavaScript

 

 

ES2016 Specifications included the  includes() method  for  Array data structure. The includes() method check if an array includes a certain element, returning true or false as appropriate.

But in ES5 we are used to performing operations like this with indexOf() method.

Using includes() method.

const array = [1,2,3,4,5,6]; if(array.includes(4) ){
console.log("true 4 was found in the array")// true 4 was found in the array
}

Let's perform the same operation with indexOf() method.

const array = [1,2,3,4,5,6]; if(array.indexOf(4) > -1 ){
console.log("true 4 was found in the array")// true 4 was found in the array
}

Using includes() method to check for NaN

 const  array = [NaN]; if (array.includes(NaN)){
console.log("true. NAN was found in the array");// true. NAN was found in the array
}

This is where things begin to fall apart with indexOf() method.

const array = [NaN];
if (array.indexOf(NaN) == -1){ console.log("NaN not found in the array");//NaN not found in the array
}

Checking for undefined with the includes() method.

const array = [, , , ,]; if(array.includes(undefined)){
console.log("true array elements are undefined");// true array elements are undefined
}

Let's see how indexOf() method will handle this operation.

const array = [, , , ,]; if(!array.indexOf(undefined) == -1 ){
console.log("true. array elements are undefined");
}else {
console.log("Sorry can't find undefined");// Sorry can't find undefined
}

The includes() method  does not distinguish between -0 and +0

const a = [-0].includes(+0);
console.log(a);//true

Typed Arrays will also have a method includes()


### Summary [dev.to](https://dev.to/) is where software developers stay in the loop and avoid career stagnation. [Signing up (for free!) is the first step.](https://dev.to/enter)


Tag cloud