There are several ways to iterate over items in JavaScript. One of the most used is for
loop. It’s an essential method, and most teach in the university if you are a computer science student.
The concept of for
loop is easy to understand. It iterates item through item, and we can control when to stop(with break), or continue(with continue), or how many times the loop should run, and get index easily, Which means you can manipulate some data or set a special condition as you need. For example, you get a bunch of news and want to render ads after the third.
for
loop is faster than other iteration methods because they are implemented using a lower-level approach, as you see the result in this image below.
source: https://jsben.ch/wY5fo
Compared with other iteration methods like forEach
or map
function, They are higher-order functions that are implemented for easy access to the item when iterating, which means this should make a slight overhead and affect the performance.
However, If you have a small number in the array, The performance of for loop or other iteration methods does not matter. The map
function or forEach
would be preferred because it easy to access the object and easy to read more than for loop method. Here, take the example:
const arr = [1, 2, 3, 4, 5];
arr.forEach(function(element) {
console.log(element);
});
arr.map(function(element){
console.log(element)
});
Compare to for loop. You have to define which item or index you want to access, which should cause a problem for
the newbie programmer.
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
It is generally best to choose the iteration method that is most appropriate for your task rather than trying to optimize for performance. In most cases, the performance difference between the different iteration methods will not be significant.
Top comments (0)