Use for…of to Loop Through Your JavaScript Arrays
A simpler way to iterate over arrays
Use `for…of` to Loop Through Your JavaScript Arrays
It can be challenging to keep up with all the latest coding conventions. What’s even harder is coming into a language with previous (outdated) programming experience and learning the right way to do things—not just a different or better way.
I originally learned to use for loops for iterating over arrays. Then I discovered the .forEach() array method, which executes a function for every element in the array. I also learned that this isn’t the optimal method for iterating over an array, and thus my search led to the for...of loop.
What is the for…of Loop?
The for...of loop is very similar to for...in, which you may have seen for iterating over objects or iterables in other languages. The for...of loop sets each item in the array to a defined variable (make this a constant).
Here are code snippets (traditional, forEach, for…of) to loop through a five-item array and print each value.let my_array = [1,2,3,4,5];// traditional for loop
for(let i=0; i < my_array.length; i++) {
console.log(my_array[i]);
}// .forEach() method
my_array.forEach((element) => {
console.log(element);
});// for...of method
for(const element of my_array) {
console.log(element);
}
Why Use the for…of Loop?
Originally, I adopted the .forEach() method because I felt like it was less to type and easier to read, but the for...of method is better for both of these things. Additionally, the .forEach() method is less performant, and it’s unable to stop mid-cycle. Additionally, .forEach() struggles with asynchronous tasks.
The for...of loop is the newest technique in a line of options for iterating over arrays. For a low-syntax and easier-to-read method that’s flexible and performs better than .forEach(), use for...of and call it a day.