$10.84

How to loop an array in javascript

Ask a question+
3

What is the best way to loop an array in javascript in point of view of performance? I know there is a for loop and forEach loop.

add comment

2 Answers

7

for is a more than faster than foreach, because for each array’s elements called function, (a function call is a more hard action).

const arr = [];
for (let i = 0; i < 1000000; ++i) {
    arr.push(Math.random());
}

console.time('test_for');
for (let i = 0; i < arr.length; ++i) {
    if (arr[i] === 4) {
        console.log('lala');
    }
}
console.timeEnd('test_for');

console.time('test_foreach');
arr.forEach((el) => {
    if (el === 4) {
        console.log('lala');
    }
});
console.timeEnd('test_foreach');

test_for: 3.012ms
test_foreach: 16.259ms

Ruben Arushanyan 2K
1

thank you for the answer!

Vazgen Manukyan
add comment
0

In JavaScript there are many ways yo loop through Array , they are 
Loop which can break  or skip(continue) an iteration
for 
while
do…while
for…of

Loop which we cannot break and skip iteration
forEach

Tip : To create An Array with number elements
var array = Array.from(new Array(10000).keys()); 
for 
let arrayLength = array.length;
for(let i = 0 ; i < arrayLength; i++) {

   let val = array[i];
}
We can break the loop using break statement 
We can skip the current iteration using continue statement.



---

2. while 
let i = 0;
let arrayLength = array.length;
while(i < arrayLength ) {
   let val = array[i];
   i++;
}
We can also use break  and continue in while loop. But when we are using while loop we need to take care of the increment  for next iteration. If we forgot the increment  part , then it may result in infinite loop


---

3. do…while
I don't prefer using do…while loop for iterating an array  . Because we don't need to perform any operation , if the array is empty. But do…while will perform action once before checking for the condition .
let i = 0;
let arrayLength = array.length;
do {
  let val = array[i];
  i++;  
} while (i < arrayLength);
We can also use break  and continue in while loop.


---

4. for…of
for(let val in array) {
    // operation  
}
We can use break  and continue in for…of loop


---

5.forEach
We need to go for forEach of we need to execute a operation on every element of the array, because we cannot break or skip iteration in this loop
array.forEach(val => {
 // operation
});

For performance Please refer here : https://jsperf.com/for-vs-foreach/654

add comment

Your Answer