Know Your Array Methods in JavaScript!
When I started working with arrays in JavaScript I always used for cycles to do operations on arrays. I was used to it from the university where we worked with C and I had no idea there are some built-in methods that would do all the dirty stuff I had to come up with each time I decided to iterate through something. As I grew up professionally I started to use these methods and fell in love with them. They make code much easier to read, there are fewer hidden bugs and it removes a lot of repetitive code.
I thought it was only my lack of knowledge and every sensible JS developer is using this. However, I took a large project that was ongoing for 10+ years with a lot of senior developers. And they always used ‘for’ cycles! It was quite a hell to figure out all cycles and the hidden tweaks they were doing. That’s why I decided to make a summary of all array methods that can iterate through arrays, write some use cases when it is good to use it and also compare analogy what the implementation would look like with for
cycle.
IMPORTANT: All array methods are synchronous! So running them on large arrays can kill your performance.
Simple loop
forEach()
This method is the most basic one. All it does is iterate through the whole array and calls provided callback on each element…