There’s a lot of possibilities and styles to write a loop in Javascript. In this article, I’ll show simple options, the readable options and least talked options.
Summary
Vanilla For loop
This examples are mostly shown in tutorials, Stackoverflow questions and documentation.
// Option 1: use a start and end value
for (i = startValue; i <= endValue; i++) {
// Before the loop: i is set to startValue
// After each iteration of the loop: i++ is executed
// The loop continues as long as i <= endValue is true
}
About the endValue: If you want to check the array lenght you should use myArray.lenght
About the i++: it means i = i + 1, that increments one by one, you're also able to use i = i + anyValueYouWant
// Option 2: use a For … in , mostly used if you have an array
for (i in things) {
// If things is an array, i will usually contain the array keys *not advised*
// If things is an object, i will contain the member names
// Either way, access values using: things[i]
}
// Option 3: use a For … of
for (i of things) {
// there's no need to use the index
// i is actually the object
}
Benefits
✔️ Very easy to learn
✔️ Readable
Downsides
❌ Uses too many lines
❌ Not appropriate to deal with Promises and async functions
While and Do-While Loop
You're also able to use the while
to se a condition to your for loop, as long it's set the beggining value, the condition and the update.
let i = 0; // beginning value
while (i < endValue) { // condition to while stop
// Do something
i++; // the update
}
Another way is to use do...while
, but remember the test condition is different from the while
. Check the documentation of do...while and while
// Alternative: use a do.. while
let i = 0;
do {
// loop body
i++;
} while (i > endValue);
Benefits
✔️ You learn to use while
and do..while
Downsides
❌ Uses too many lines
❌ If you forget any of your setup, the while
loop will run endlessly
Calling forEach
When you're working with arrays, you might have found a whole set of method to deal with, one of them is forEach
. (Documentation link).
myArray.forEach(element => {
// Do your operation here
console.log(element)
});
Benefits
✔️ Few lines of code
✔️ Loop through all the elements of your array
Downsides
❌ Not appropriate for Promises and aysnc functions ( instead use Promise.all )
❌ You shouldn't use in cases that don't actually need to cover other conditions
If I can't use forEach, what should I do?
Follow this guide from Stackoverflow discussion, I'll share a fraction of great options thata lot of users shared.
every
(spec | MDN) - stops looping the first time the callback returns a falsy valuefilter
(spec | MDN) - creates a new array including elements where the callback returns a truthy value, omitting the ones where it doesn'tmap
(spec | MDN) - creates a new array from the values returned by the callbackreduce
(spec | MDN) - builds up a value by repeatedly calling the callback, passing in previous values; see the spec for the detailsreduceRight
(spec | MDN) - likereduce
, but works in descending rather than ascending order
Top comments (0)