Trouble With Loops
Loops are one of the first manipulations I learned about in Javascript. They are easy to write and simple to think about . It becomes tempting to avoid learning new ways to manipulate arrays and just use loops everywhere.
Relying on loops can become a problem because loops are synchronous. This means that they can only manipulate data that already exists. You run into problems when you have to deal with asynchronous data, like events that have not happened yet.
Asynchronous programming is much easier than it sounds. You can build a lot of asynchronous programs by using the Map, Reduce and Filter methods.
map()
Use it when: You want to translate values in an array into another set of values.
Example: convert dollar amounts in Euros.
What it does: Map traverses the array from left to right. It invokes a function (in this case, eachAmount * .93) on eachAmount (which you can call whatever you want). When the method is finished mapping all the elements it returns a new array with all the translated elements.
reduce()
Use it when: You want a total based on values in an array.
Example: Sum up a series of euro amounts.
What it does: Reduce invokes a function (in this case, total + amount) on each amount in an array. For reduce to work, it must start with an initial total value (in this case 0) to add the first amount to . When the method reduces all the values it returns the total value.
filter()
Use it when: You want to remove unwanted values from an array.
Example: Remove any euro amounts lower than 30
What it does: Filter invokes a function (in this case, euro >= 30) on each amount in an array. When the method has filtered all the values it returns a new array with all values that returned true.
Learning new ways to manipulate arrays makes your code easier to read. In a loop we need to check 5 pieces of information to determine what is going on. Where the loop starts, where it ends, how it increments, what is being looped and what is happening in the loop. On the other hand, euros.filter(euro => euro >= 30) is easier to read and has fewer places to make mistakes.
Learning how to write code that is easy to read is important because the better you get, the less code you tend to write. You start spending more time improving old code, which means reading code that you have already written. You also start working with other people and having to read their code. Being able to write readable code makes it easier for you to understand code that isn’t always phrased as a loop. Most importantly, writing readable code is easier to understand and it makes you more pleasurable to work with.
Last updated
Was this helpful?