Loops in Javascript: Use Cases of .map and .filter

I was attempting to understand more functional style of loops mentioned in the article by Joel Thomas named ‘Rethinking JavaScript: Death of the For Loop’. (http://bit.ly/2pT1jlA) Then, I began to wonder use cases of ‘for’ loops opposed to .map and .filter methods all together, so this will be a refresher.

I wanted to think through the pros/cons of these methods while ultimately learning more about the functional programming style. Things to consider when refactoring code are speed and memory. Also, which is more readable, maintainable and hackable? Lastly, what is the scope is paired with the function you’re using and how does this play into your strategy?

The ‘for’ Loop

var money = [5, 10, 20, 50];
for (i = 0, l = money.length; i < l; i++) {
//should return the following
=> undefined
var words = ["Let", "me", "clear", "my", "throat"];
for (i = 0, l = words.length; i < l; i++) {
//should return the following
3, 2, 5, 2, 6
=> undefined

While it’s typically the first loop you’re introduced to and fairly simple to write, the for loop if often times ‘wordy’ and the other loops claim to be more re-usable. Countless developers online are opinionated about usage of a ‘while’ , ‘for.each’, ‘.map’, ‘filter’ methods, but you have to work with what you know or expand what you know and then select the proper tool for the job. But before we go any further let’s look at similar example in a ‘.map’ style.

The ‘.map’ loop

money = function (element) {
return element * 2;
myArray = [5,10,20,50];
// should return => 
[ 10, 20, 40, 100 ]
djcool = function (element) {
return element.length;
wordsArray = ["Let", "me", "clear", "my", "throat"];
//should return => [ 3, 2, 5, 2, 6 ]

There is something gratifying about recalling the entire ‘for’ loop and seeing it execute, but the ladder is undeniably easier to read out, and for anyone that recently switched languages, to digest the syntax .

The ‘.filter’ loop

var isPuppy = dog => dog.months < 10
var getName = dog => dog.name
var getPuppyNames = dogs =>

var dogs = [
{ name: 'Moco', months: 6 },
{ name: 'Nacho', months: 14 },
{ name: 'Pancho', months: 4 },
{ name: 'Armando', months: 2 }
puppers = getPuppyNames(dogs);
//should return => [ 'Moco', 'Pancho', 'Armando' ]

Another contrived example, but easily digestible. The ‘filter’ is iterating through the array and determining the dogs age meet the puppers boolean logic then defining and returning those names that were below 10 months


Ultimately, I’m still learning which instances call for a particular tool, when to use certain methods, but everything I’ve read involves some form of asking: which is more readable, maintainable, hackable?