Something to be careful of is that JavaScript arrays are slow as molasses at the antarctic. As such using Array.includes / indexOf instead of multiple || might save you some typing, but it executes many, many times slower.

So if you need to optimize for speed, don't do that. Note, I'm not saying don't ever do that as if it's only being run once it probably doesn't matter... but if it's inside a long loop it can start to matter a lot.

I made that mistake very early on in my learning JavaScript back arounc 2002. Having come from decades of writing code for compiled languages I was used to using ACTUAL arrays as lookup tables for complex calculations to speed things up. Found much to my surprise that it was faster to perform a divide and a Math.ATAN2 than it was to have a lookup table with one multiply and one divide in a JS array for the 640 possible outcomes I needed.


angle = Math.Atan2(small/large);

Should not be faster than:

angle = lookup[Math.floor(small * 640 / large)];

But it is. In most any compiled language, C, Pascal, Ada, etc, that lookup to an array should be faster since ATAN2 is a complex float operation, but with JS it’s faster to do math than it is to access arrays.

This stems from the simple fact JS arrays are not ACTUALLY what “real” programmers consider to be arrays. They are pointer based lists masquerading as Arrays. Hence why the bigger the array, the longer it takes to access higher indexed values.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store