20 JavaScript tools to blow your mind

05. Replace 'for' loops with 'map' to keep things simple

Let’s pretend we have an array of numbers and we’d like to produce another array by doubling all of the numbers from the first array. One way to do this is to declare an empty array, write a for loop, and set a number in the second array by looking up the index on the first array and doubling it.

 Or we could use a more concise solution by mapping an array to another array:

[1, 2, 3].map((num) => num * 2); // [2, 4, 6]

06. Replace 'for' loops with 'filter'

This time, let’s pretend we have an array of numbers and we’d like to produce another array containing only the even numbers from the first array. Again, one way of doing this would be to declare an empty array, write a for loop, and write an if statement to check if the number at the index is even (for example).

Or, we could use the filter method available for arrays:

[4, 7, 2, 3].filter((num) => num % 2 === 0); // [4, 2]

07. Use 'reduce' instead of 'for' loops

For this exercise, let’s calculate the sum of all of the numbers in an array. One way to do this would be to declare a variable that has zero as its initial value. Then, we would write a for loop and traverse our array, taking each number and adding it to our newly created variable. 

Or we could use the reduce method:

[7, 2, 4].reduce((a, b) => a + b); // 13

Of course, we could combine all three concepts by multiplying all the numbers by 7 and adding all the numbers that are smaller than 20:

[3, 2, 1, 6]
 .map(num => num * 7)
 .filter(num => num < 20)
.reduce((a, b) => a + b); // 21

08. Take advantage of immutability

Data immutability is a common concept in functional languages. Immutable data allows programs to detect changes early on by comparing object references, instead of having to continually check and iterate through objects to see if we need to refresh the data on the screen.

Since, by default, objects and arrays are not immutable in JavaScript, there is a library to help accomplish this. It’s called Immutable.js and it was developed and open-sourced by an engineering team at Facebook.

Next page: Server-side JavaScript with Node.js