Which JavaScript for loop should I use?
When given a choice of 4 seemingly different ways to do the same thing, I've always been the person that wants to know what the difference is? To often we can blindly write code the way the person before us did and not understand the reason to do it a certain way, but what if the scenario has changed. When multiple options exist there's usually a reason why. It can be a language style improvement to make things easier to write, but more often than not there's a fundamental difference in what it actually does.
So, for loops, four seems like a lot, gotta be some differences right?
for
This is likely to be the first type of for loop you encounter when learning to program. It's a very manual type of loop where you create a initial expression, a condition expression to keep running the loop and an increment expression.
1for (let i = 0; i < 5; i++) {2 console.log(i);3}45// Result:6// 07// 18// 29// 310// 4
The big downside of the for loop is it doesn't actually loop through a collection. e.g. If you had an array and wanted to loop through each of it's objects you could do this as follows:
1const arr = ['a', 'b', 'c'];23for (let i = 0; i < arr.length; ++i) {4 console.log(arr[i]);5}
In effect the loop is incrementing a number and you then use that number to access the position of the array. The result is you have more code to write that isn't serving any real purpose.
However as this is a much more manual loop process you have far more control over the loop. e.g.
- You could increment by a different number.
- You could go backwards.
- The condition might not be linked to the length of an array.
- You might not even be looping through an array.
Pros
- Potentially faster in performance.
- Break statement can be used to come out of the loop.
- It works with the await keyword.
- Not just for looping through arrays.
Cons
- Not as readable as others.
- You have more code to write.
for...in
You probably don't want this one. Here's an example:
1const arr = ['a', 'b', 'c'];23for (const i in arr) {4 console.log(arr[i]);5}67// Result:8// "a"9// "b"10// "c"
Although we're now specifically looping through a collection like an array and don't need to do all of that i < array.length stuff, what we're given isn't the object in the array but a property name to access it on the object.
Here's another example:
1const arr = ['a', 'b', 'c'];2arr.foo = 'John'34for (const i in arr) {5 console.log(arr[i]);6}78// Result:9// "a"10// "b"11// "c"12// "John"
That looks a bit weird! The for...in loop doesn't just loop through an array, it loops through an objects enumerable properties, which could be the items in an array, but it could be other stuff too.
For this reason, unless your doing something quite niche its probably not the loop you are looking for and is likely to cause you an issue which your objects has one more property than you were expecting.
Pros
- Can loop through all the enumerable properties on an object.
Cons
- Looping through all the properties of an object isn't likely what you want.
forEach
As the name implies, a for each loop will iterate through each element in an array. Here's an example:
1const arr = ['a', 'b', 'c'];23arr.forEach((i) => {4 console.log(i);5})67// Result:8// "a"9// "b"10// "c"
The forEach function takes an anonymous function as a parameter and will then call that function for each object in the array, passing in the object from the array.
This offers a big improvement over the initial for loop as we have a lot less code to write and we're actually given the object rather than a variable to go an find it.
However there are some downsides due to it effectively being a function call passing an anonymous function to execute.
Firstly you can't stop the forEach part way through. With the others you can use the break keyword to stop the iteration.
Secondly there's added confusion around the scope of what this is. Assuming your function is in a class, unless you use the arrow syntax (as in the example) you won't be able to access any of the other functions in your class as passing a regular function would change the scope.
1// This works2class foo3{4 myFunction() {5 const arr = ['a', 'b', 'c'];67 arr.forEach((i) => {8 this.outputValue(i)9 })10 }1112 outputValue(x) {13 console.log(x);14 }15}1617// This Doesn't18class foo19{20 myFunction() {21 const arr = ['a', 'b', 'c'];2223 arr.forEach(function(i) {24 this.outputValue(i)25 })26 }2728 outputValue(x) {29 console.log(x);30 }31}
You also can't use an await within the foreach loop. e.g.
1async function run() {2 const arr = ['a', 'b', 'c'];3 arr.forEach(el => {4 // SyntaxError5 await new Promise(resolve => setTimeout(resolve, 1000));6 console.log(el);7 });8}
Pros
- Much shorter to write and easier to read.
- Iterator provides the object from the array.
Cons
- Easy to mess up context of this.
- No way to break the loop.
- Async/Await doesn't work on functions within the loop.
- Can only loop through arrays.
- It's performance is slower (nice article here comparing the performance differences), not to such an extent it would matter on a small object, but large objects could start to take a hit.
for...of
When looping through an array, the for...of loop combines the best of all the other loops. It has the same simple syntax of the for...in loop but instead of enumerating over enumerable properties, it loops through the iterable objects such as the items in an array.
Like the forEach loop you are provided with the object in the array rather than it's index or property name.
1const arr = ['a', 'b', 'c'];23for (const i of arr) {4 console.log(i);5}67// Result:8// "a"9// "b"10// "c"
You can also break the loop and access properties outside of the loop.
1const stopValue = 'b'2const arr = ['a', 'b', 'c'];34for (const i of arr) {5 console.log(i);6 if (i == stopValue)7 break;8}910// Result:11// "a"12// "b"
Pros
- Lowest amount of extra code to write.
- Iterator provides the object.
- Doesn't use an anonymous function so scope doesn't change.
- Loop can be stopped as needed.
- Async still works.
- Works with more than just arrays.
Cons
- Have to be looping over the iterable items in an object.
- Can't easily access the index value.
Conclusion
If you want to iterate through something like an array, for...of would be my recommendation to use. A for...in loop is likely to be less relevant but has its place, and for all other loops which don't relate to the objects in an array a good old for loop still has it's place.