Replacing for loops with JavaScript array methods
The for
loop is the most basic way of iterating over an array in Javascript. It looks familiar for programmers coming from other languages like Java¹ and it gets the work done. But in JavaScript² you have better options.
The problem with "for"
loops
Take the following code snippet. Try to give resA
, resB
, and resC
more useful names:
I bet that you had to spend some time mentally parsing the code and removing the “useless” bits. Even if you are an experienced JavaScript developer. for
loops are a generic iteration statement and as such they tend to “blur” the intent of the code. They make it harder to understand and its purpose harder to identify.
JavaScript array methods, though, make the iteration implicit, and are purpose-specific. If you use them, your code will become more concise and self explanatory. It will be easier to read and understand.
Let’s rewrite the snippet above using array functions:
Once you know what each function does, renaming the variables is straightforward³:
The resulting code is declarative, easier to read and understand, and less error-prone (did you spot the bug in the first snippet?).
Some guidelines for choosing the right array method
Take this as an exercise: don’t write for
loops. Never. Force yourself to use array methods instead. Every time you write a for
loop, think about your intention. What do you want to get as a result?
- If you are searching for an element, use
find
. - If you are trying to get an element’s index, use
findIndex
,indexOf
,lastIndexOf
. - If you want a boolean value telling something about the array as a whole, try
includes
,some
,every
. - If you want all the elements meeting some condition, use
filter
. - If you want a new array with each original element transformed, use
map
. - If you want anything else, maybe it’s time for
reduce
orreduceRight
.
Oh, and even if you just want to iterate over each element to cause some side effects… use forEach
!
Notes
¹ Most of the people doing JavaScript at Trabe started as Java developers.
² I mean ECMAScript 2016.
³ This is the trade-off: you have to know what each function is supposed to do to understand the code. Anyway, dealing with arrays is one of the main things we do as developers. Knowing the array API is a skill every JavaScript developer should master.