Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Obsessed with React and teaching. I help people become Frontend Developers. Living with my fiancee and Yorkshire Terrier 🐶 in Poland.
Image by Dan Freeman from Unsplash

JavaScript Arrays And How To Avoid Loops

Nov 4, 2020
6 min read

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:
Assignment: Remove all numbers less or equal to 10.
Loop solution:
✅ Filter numbers in an array:
Assignment: Sum all numbers.
Loop solution:
✅ Reduce numbers to create a sum:
Assignment: Find index of number 15.
Loop solution:
✅ Find index by using an indexOf method:
Assignment: Check if all numbers are greater or equal to 10.
Loop solution:
✅ Check if condition is true to all numbers:
Assignment: Check if any number is greater or equal to 10.
Loop solution:
✅ Check if condition is true to any number:
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. ❤️
logo with a rocket of the BigDevSoon application

Level up your Frontend skills

Code real-world projects based on Figma designs.
spread the word
Did you like this post? Share it with the world! 🌐