How to loop an array in javascript

Ask a question
2

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.

Coin iconoffer bounty
add comment

1 Answer

1

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

1

thank you for the answer!

Vazgen Manukyan
add comment

Your Answer