HI WELCOME TO KANSIRIS

Includes() vs indexOf() in JavaScript

Leave a Comment
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()

let array = Uint8Array.of(2,6,4);
console.log(array.includes(4));//true


Summary
The includes method finds NaN and undefined whereas the indexOf method doesn't.
The includes() method does not distinguish between -0 and +0(This is not a bug, but clearly how javascript works.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.