Part III of “ Weird questions from my first month of coding”
Here I assume you know how to use each iterator. It’s ok if you get confused by them or if you’re note sure of when to use them, though. It took me a few weeks to understand the proper use of different iterators, and I hope this post will help you clear this out.
Use map when you want to transform an array without changing its original values.
IRL (In real life): You can use this method to iterate through API data to show each entry in your website — instead of hard coding them in each div, for example.
Use filter when you want to select certain elements in your array. When an element meets the conditions given in your function (in other words, it’s true), it is included in the returned array:
IRL: If you have a database of clients and need to find only those over 18 yo, you can use filter to do it.
forEach is useful when you simply need to run a function through each item in the array, with no need to get a return.
IRL: You can use forEach to process and save data in your database.
If you need your array to be reduced to a single value , reduce is a very elegant solution:
IRL: The classic example is to get the sum of numbers in a certain array. For example, if you have a catalog of books in JSON format, you can check how many of those books were published when your grandma was your age.
It’s useful to use this iteration when you know how many times you want to execute a function.
If you don’t know in advance how many times to execute a function, a while loop might be a good idea. In real life, this iteration could be used to slideshow your phone pictures until you tap stop, for example. Or if your gaming character keeps running for as long as you press an arrow key. In both cases, you don’t know beforehand when the user will interrupt the loop. But be careful: if you set while condition to true, you may accidentally create an infinite loop Oo
Please note that there might not be one right answer to your function. If you look closely, you’ll see that a for loop can well do the job of a map or reduce method, or that while loops work fine replacing for loops. But the more we code, the more we see that some options fit better than others. You may pick a certain method to make your code more readable, or you might decide for another one for increased performance. In any case, if you know your tools you have a larger set of options to make your code more efficient and friendly to the machines and to your fellow humans too :)
“Weird questions from my first month of coding” series
Part I: How array indexes & values work in for loops
Part II: How to write functions that go inside a filter method