6 Powerful Ways of Replacing for Loops in JavaScript
Learn how to replace for loops in JavaScript with six helpful methods and write more concise and readable code.
Welcome! Let me show you a few helpful methods that you can use to replace for
loops in specific situations, particularly situations related to arrays.
Throughout this article, I will show you practical examples to illustrate how these options can replace for
loops in JavaScript and still get the same output.
Let's begin! ๐
๐น The .forEach()
Method
This first method is very helpful to replace for
loops when we use them to iterate over the elements of an array.
With a for
Loop
If you have ever written something like this:
let myArray = [1, 2, 3, 4];
// Iterate over the array
for (let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
With the Method
Then, you will find that using the .forEach
method instead can be more concise and easier to read:
let myArray = [1, 2, 3, 4];
myArray.forEach(element => {
console.log(element);
});
The output is the same in both cases is:
1
2
3
4
๐ก Tip: this method is super helpful when you need to iterate over the elements of an array and use them directly. However, it will not give you access to the index of the element. If you need to keep track of the indices, then I would suggest choosing a different alternative or keeping track of this with a counter.
This is the general syntax:
array.forEach(element => {
// Do this
});
Let's analyze this syntax line by line:
First, we call the method on the array:
array.forEach()
.Then, within parentheses, we pass an arrow function as an argument. This arrow function will automatically take each element of the array as an argument, one by one. This is an example of the arrow function:
element => { // Do this }
.Within the curly braces, you should write the code that should run for every element in the array. It is equivalent to what you would write inside the body of the
for
loop.
This is a great alternative to the traditional for
loops if you need to iterate over the elements of an array.
๐ธ The .find()
Method
Great! Now let's talk about the .find()
method. If you have ever tried to find the first element that matches a specific criterion, then you might have written a for
loop quite similar to this one, right?
With a for
Loop
let myArray = [4, 5, 6, 7, 8];
let elementFound;
for (let i = 0; i < myArray.length; i++) {
if (myArray[i] > 6) { // Criteria.
elementFound = myArray[i]; // Assign the element.
break; // Stop the loop.
}
}
console.log(elementFound);
The output is:
7
With the Method
Well... let me tell you that even if this for
loop works correctly, there is a much better way to write this in JavaScript with the .find()
method.
According to MDN Web Docs:
The
find()
method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function,undefined
is returned.
This is the general syntax:
array.find(element => /* Condition */);
๐ก Tip: this method returns the first element in the array that matches the criteria. If the condition is True
, the current element is automatically returned and the method call stops immediately.
In our example, the equivalent code can be written in just three lines of code:
let myArray = [4, 5, 6, 7, 8];
let elementFound = myArray.find(element => element > 6);
console.log(elementFound);
Let's analyze the syntax line by line:
We call the method on the array:
myArray.find()
.Then, we pass an arrow function as an argument:
element => element > 6
.The arrow function takes each element of the array as an argument.
It returns the first element that matches the criterion (if
element > 6
isTrue
).If none of the elements matches the criterion,
undefined
is returned.
The output is exactly the same:
7
This is awesome, right? We can find an element with just three lines of code. ๐
๐น The .filter()
Method
And we can also extend this idea even further to find all the elements that match certain criteria. If you have ever tried to implement this with a for
loop, your code must have been similar to the following example.
With a for
Loop
let myArray = [4, 5, 6, 7, 8];
let elementsFound = [];
// Iterate over the elements of an array.
for (let i = 0; i < myArray.length; i++) {
if (myArray[i] > 6) { // Condition.
elementsFound.push(myArray[i]); // Add the element to the array.
}
}
console.log(elementsFound);
In this example, we are finding all the elements in the array that are greater than 6. The output is:
[7, 8]
With the Method
But let me tell you that there is a much more concise way of doing exactly the same thing with the .filter()
method.
This is the general syntax:
array.filter(element => /* Criteria */);
According to MDN Web Docs:
The
filter()
method creates a shallow copy of a portion of a given array, filtered down to just the elements from the given array that pass the test implemented by the provided function.
The equivalent code for our example would be:
let myArray = [4, 5, 6, 7, 8];
let elementsFound = myArray.filter(element => element > 6);
console.log(elementsFound);
Let's analyze this syntax line by line:
First, we call the method:
myArray.filter()
.Then, we pass an arrow function as an argument. This arrow function will take each element in the array as an argument.
Only the elements that meet the criteria will be added to the final array.
In this example, there is one criterion, and that is
element > 6
. If this isTrue
, then the element is added to the final array.
๐ก Tip: the .filter()
method returns an array with all the elements that meet the criteria.
In this example, the output would be:
[7, 8]
This is exactly the same output that we had previously, but with much more concise code.
๐ธ The .slice()
Method
Traditional for
loops can also be used to get a "slice" of an array, like in the following example.
With a for
Loop
let myArray = [4, 5, 6, 7, 8];
let newArray = [];
let start = 1; // Inclusive
let end = 4; // Non-inclusive
for (let i = start; i < end; i++) {
newArray.push(myArray[i]);
}
console.log(newArray);
The output is:
[5, 6, 7]
With the Method
However, we can do this with just one line of code if we call the .slice()
method.
According to MDN Web Docs:
The
slice()
method returns a shallow copy of a portion of an array into a new array object selected fromstart
toend
(end
not included) wherestart
andend
represent the index of items in that array. The original array will not be modified.
This is the general syntax to call this method with zero, one, and two arguments:
array.slice();
array.slice(start);
array.slice(start, end);
๐ก Tip: if you only pass one argument, the slice will start at that index and it will include all the elements in the array until it reaches the last element.
๐ก Tip: if you don't pass any arguments, all the elements will be included in the shallow copy of the array.
This is the equivalent code for our previous example:
let myArray = [4, 5, 6, 7, 8];
let newArray = myArray.slice(1, 4);
console.log(newArray);
The output is:
[5, 6, 7]
This is super helpful. We can get a slice of the array with just three lines of code.
๐น The .map()
Method
Now let's talk about the .map()
method. This method is very helpful when you need to generate new values based on the existing values of an array. For example, multiplying them by a specific value.
With a for
Loop
If we try to do this with a for
loop, we will have something like this.
In this example, we are multiplying all the elements of an array by 3 and then we are appending them to a new array.
let myArray = [4, 5, 6, 7, 8];
let newArray = [];
for (let i = 0; i < myArray.length; i++) {
newArray.push(myArray[i] * 3);
}
console.log(newArray);
The output is:
[12, 15, 18, 21, 24]
With the Method
But there is an even better way to write this with the .map()
method. Let's see.
According to MDN Web Docs:
The
map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.
This is the general syntax:
array.map(element => /* Expression */)
Let's analyze the syntax line by line:
First, we call the method on the array:
array.map()
.Then, we pass an arrow function as an argument.
This arrow function takes each element in the array as an argument and it returns the value of the expression for each element.
The value of the expression is added to a new array and this final array is returned when all the elements have been selected.
In our example, the equivalent code would be:
let myArray = [4, 5, 6, 7, 8];
let newArray = myArray.map(element => element * 3);
console.log(newArray);
๐ก Tip: We are multiplying every element by 3 because this is the expression that we wrote inside the arrow function (element * 3
). You can write any valid expression to generate the new values.
The output is:
[12, 15, 18, 21, 24]
This is awesome, right? The .map()
method is super powerful and I totally recommend using it for this use case.
๐ธ The .reduce()
Method
If you have ever tried to perform an operation with the values of an array that results in a single value, the .reduce()
method is exactly what you need.
With a for
Loop
To find the sum of all the elements in an array with a traditional for
loop, we could write something like this:
let myArray = [4, 5, 6, 7, 8];
let sum = 0;
for (let i = 0; i < myArray.length; i++) {
sum += myArray[i];
}
console.log(sum);
The output is:
30
With the Method
But... you guessed it! There is a much more concise way of doing exactly the same thing in our code. We just need to use the .reduce()
method.
According to MDN Web Docs:
The
reduce()
method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.
There are many ways to call this method, as you can see in this article by MDN Web Docs. However, the syntax that you will find most frequently is:
array.reduce(callbackFunction, initialValue);
This method takes two arguments:
A callback function: a function that will be called recursively to find the total value.
An initial value: to start the calculations.
Now let's talk about the callback function. The callback function will have the following structure:
function (accumulator, currentValue) { /* โฆ */ }
accumulator
is the accumulated value so far. This is essential to keep track of the value that has been accumulated during previous recursive calls.currentValue
is the value of the array that is currently being processed. Remember that this method will process all the elements in the array to find the final value.
๐ก Tip: since .reduce()
is recursive (it calls itself until it reaches a base case), initialValue
will be passed to the callback function as an argument and it will be the first value of currentValue
when the process begins.
This is an example to find the sum of an array:
let myArray = [4, 5, 6, 7, 8];
let sum = myArray.reduce((partialSum, elem) => partialSum + elem, 0);
console.log(sum);
We call
myArray.reduce()
.We pass an arrow function and the initial value within parentheses. Notice the comma that separates these two arguments:
((partialSum, elem) => partialSum + elem, 0)
The arrow function is the first argument and the initial value is the second argument.
The arrow function takes two arguments: the accumulator and the current value.
The accumulator will be updated with the partial sum and the value of the element will be updated in each recursive call.
This way, we will accumulate the sum of the elements until we get the total sum of the elements of the array.
The output will be:
30
Video Tutorial
In this video from my YouTube channel, you can also review these methods and see them in action as I type the code. You are welcome to watch it! ๐
๐น Summary
Awesome. We covered six ways to replace for loops in JavaScript with helpful array methods. This is a summary of what you learned:
There are many helpful methods that we can use in JavaScript to replace
for
loops, especially for iterating over arrays.The
.forEach
method is helpful to do something with every element in an array.The
.find
method finds the first element in an array that matches specific criteria.The
.filter
method finds all the elements in an array that match specific criteria.The
.slice
method creates a slice of an array within a given range of indices.The
.map
method transforms the elements of an array and creates a new array with these new values.The
.reduce
method is helpful to reduce an array into a single value. It takes all the elements of the array and accumulates a value based on the value returned from the function calls. It returns this final value after processing all the elements in the array.
๐ป Thank you for reading my article. I hope you liked it and found it helpful.
If you would like to find more coding tutorials, follow me on YouTube (Coding with Estefania) and Twitter (EstefaniaCassN).
Have an awesome day. ๐