Home > Back-end >  Using includes() method when having only one element in an array is it efficient?
Using includes() method when having only one element in an array is it efficient?

Time:09-20

Does the below code blocks vary in performance especially when the array has only one element?

myArray.includes(anElement);

and

myArray.length === 1 && myArray[0] === anElement

Please tell which is a good coding practice and also tell about any performance issues in the above two scenarios.

CodePudding user response:

When the array has only one element - the only difference is the length check. So if you are running this in a loop for a long time - probably you will see a difference because of that.

But the problem here is that you should not assume that the array has only one element unless you checked it previously, then it's the same.

If the array may contain more than one element, then the logic between these two is different and the comparison doesn't make sense.

Bottom line - to have them with the same logic you will do the same work. So just make it readable as @Xion 14 suggested.

  • Related