Image by Dan Freeman from Unsplash
DESCRIPTION
Arrays exist in every programming language. It's a data structure best suited for storing multiple values. And, for doing various operations on these values, often called as a collection.
Introduction
It's always best to learn by doing. Take a look at the below code example, study and execute it step by step.
Let's learn how to utilize array methods to do useful operations on the entire collections.
Useful array methods & avoiding loops
Changing original array items, pushing to it results in mutating which can introduce unwanted, side effects and makes code much more difficult to maintain. Let's aim for a declarative, functional approach with immutability in mind. Go through the below examples to see how we can easily achieve that with less code and more semantics.
1. .map()
Assignment: Multiply all numbers by 2.
Loop solution:
✅ Map numbers in an array:
2. .filter()
Assignment: Remove all numbers less or equal to 10.
Loop solution:
✅ Filter numbers in an array:
3. .reduce()
Assignment: Sum all numbers.
Loop solution:
✅ Reduce numbers to create a sum:
4. .indexOf()
Assignment: Find index of number 15.
Loop solution:
✅ Find index by using an
indexOf
method:5. .every()
Assignment: Check if all numbers are greater or equal to 10.
Loop solution:
✅ Check if condition is true to all numbers:
6. .some()
Assignment: Check if any number is greater or equal to 10.
Loop solution:
✅ Check if condition is true to any number:
7. .includes()
Assignment: Check if number 15 is included in the numbers array.
Loop solution:
✅ Check if number is included:
Bonus
I described couple of more methods, techniques to work with arrays, example below:
Summary
I have lots of fun with immutability and enjoy it to the max. Don't remember when I wrote a loop last time. Mostly working on Frontend tho, might be totally different when working with Backend as it's all about optimizations then. Find your balance.
Declarative, functional programming is cool but there is nothing wrong with mutations too. Using
break
or loops might be necessary, don't limit yourself to one style. It's all about conventions when working in a team and if you mostly work solo, find what suits you the best.There are more array methods in JavaScript, but I mostly focused on the ones which avoid mutations. I hope you learned something along the way.
Big thanks for reading the article, you're awesome! 🙇♂️
You can also find me on:
Thanks for all the support. ❤️