🟡 JS: forEach, map, reduce, filter & sort overview 🟡

These 5 functions have become a staple of working with arrays in JS since they were introduced.

Here's a quick overview of what each one does and how we can use them. 🧵 1/8
--
#100DaysOfCode #developer #DEVCommunity
Before diving into the list, I wanted to cover what allows all of these functions to exist. They are all examples of 'Higher-Order Functions'.

This is when a function operates on another. I covered it further in the thread linked. 2/8

🔗 https://twitter.com/MrConerMurphy/status/1364206725826564109
1️⃣ .forEach()

.forEach() allows us to loop over an array and access each item individually, similar to how a for loop would do it but in a nicer syntax.

❗ You can't return values from a .forEach() if you want to return values you need to use .map(). 3/8
2️⃣ .map()

As mentioned for .forEach(), if you want to iterate over an array, manipulate the value(s) in some way & return the final results, you need to use a .map()

.map() and .forEach() are very similar, to tell which to use think if you need to return a new array. 4/8
3️⃣ .reduce()

.reduce() is a special method that is often one of the hardest to learn due to how versatile it is.

With a .map() you operate on the values & return. But, with .reduce(), you can do pretty much anything.

In this example, I sum the values in the array. 5/8
4️⃣ .filter()

.filter() does what it says on the tin, it filters the array down to a smaller size based on if each value passes/fails the filter condition.

In this example, I check if the value is an even number by checking if the remainder of dividing by 2 is 0. 6/8
5️⃣ .sort()

.sort() allows us to sort an array based on a compare function we pass in.

Sort works by taking 2 values (a,b) and checking if one is larger than the other to ascertain the correct order. This is then returned as a new array. 7/8
If you found this thread helpful, please consider sharing it so others can also find it helpful. Also, if you wish to see more content like this please consider following my account. 😄
You can follow @MrConerMurphy.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: