DEV Community

Discussion on: A neat little trick with JavaScript's indexOf()

Collapse
 
werninator profile image
Patrick Werner • Edited

Thanks for your opinion and the URL, I'm not trying to convince anyone to use this piece of advice/tip or how you wanna call it - everyone has to decide on his/her own if they want to experiment with it or even use it. I'll use it because my projects mostly consist of legacy code from 2002 that is much worse than a little operator combined with a non-efficient, but established method :c)

Collapse
 
bgadrian profile image
Adrian B.G.

Do not get me wrong, I commented because I felt that junior devs (that are usually attracted by this kind of posts) should know the other side of the story. You presented the story only for one side so I felt compelled to add the side effects.

Also experimenting is good, I recommend to you and readers:

  • read how and why this trick works
  • test the operator on negative and positive numbers, zero and minimum-maximum numerical values
  • do some benchmarks with jsperf on different methods of searching a specific value in a specific list, including with same types indexOf(1), indexOf("1")
  • learn bit operators, you will not used them often, but when you need them they will bring that extra performance boost, most likely in a critical path of your app

As for legacy code, too bad they don't evolve over time, as our skills and knowledge growth, our code should too.

As other said, Array.includes was added to ECMAScript just because indexOf > -1 was very popular. but, they are not fully interchangeable because they do not use the same comparison algorithm: results of indexOf and includes may be different.

[1,NaN,3].includes(NaN)
true
[1,NaN,3].indexOf(NaN)
-1