3 Ways to Loop Over an Array Using Node.js
Often in software, we need to repeat an action multiple times. Loops are one way to acheive this.
We'll cover all the ways you can loop over an array in Node.js.
Let's get started!
Table of Contents
While
The while
loop has the following syntax:
const array = [0, 1, 2, 3, 4, 5]
let i = 0
while (i < array.length) {
console.log(array[i])
i++
}
While the condition is true
, the code in the loop body will continue to be executed.
Each execution of the loop body is called an iteration. For example, the loop
above did 6 iterations until it had gone over all the values in the array.
Also, if the i++
was not in the loop body, the loop would continue forever.
Do/While
This is another way to do a while loop, where the conditional check is moved below the loop body.
Here's what the syntax looks like:
const array = [0, 1, 2, 3, 4, 5]
let i = 0
do {
console.log(array[i])
i++
} while (i < array.length)
The loop will execute the body first, then check the condition. Then it will execute the same body again while the condition is truthy.
This syntax should only be used when you want the body of the loop to execute at least once, regardless of the condition being truthy on the first iteration.
Usually the other form of the while
loop is preferred.
For
The for
loop is the most widely used loop.
And it looks like this:
const array = [0, 1, 2, 3, 4, 5]
for (let i=0; i < array.length; i++) {
console.log(array[i])
}
Let's examine each part of the loop algorithm:
Loop Begins
→ (if condition → execute code in body and increment step count)
→ (if condition → execute code in body and increment step count)
→ (if condition → execute code in body and increment step count)
→ (if condition → execute code in body and increment step count)
→ ...
If you are new to loops, it could help to go back to the example and reproduce how it runs step-by-step on a piece of paper.
You should now have a better feel for looping through arrays with Node.js.