Image credit to Andrew Doane. Thank you, Andrew.

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. Loops make you tell the computer how you want to do something. The trouble with loops is that as they become more and more complex they become harder and harder to read. There are array methods that act as shorthands for a lot of the more common use cases for loops. A shorthand is nice because it makes your code easier to read and reason about. Here are three of the most common array methods and how to use them:

map()

Use it when: You want to translate values in an array into another set of values.

Example: convert dollar amounts in Euros.

const dollars = [32, 45, 50];



const euros = dollars.map(eachAmount => eachAmount * .93);



//.93 was the exchange on google on 21st Jan 2017 euros // [29.76, 41.85, 46.5] // copy the above code into your console to see it work

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.

const euros = [29.76, 41.85, 46.5];



const sum = euros.reduce((total, amount) => total + amount, 0); sum // 118.11 // Refresh your browser before you copy the code into your console. We already declared euros using const in the previous example. You cannot redeclare the value of a constant variable.

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

const euros = [29.76, 41.85, 46.5]; const above30 = euros.filter(euro => euro >= 30); above30 // [ 41.85, 46.5]

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.