🔁 JS array looping

On this page

There are a few different ways to loop over an array:

for Jump to heading

for (var i = 0; i < array.length; i++) {
array[i]
}

forEach Jump to heading

array.forEach(function (i) {
array[i]
})

for in Jump to heading

for (var i in array) {
array[i]
}

for…of Jump to heading

for (var i of array) {
array[i]
}

Test results Jump to heading

Test case name Result
for for x 4,680,671 ops/sec ±0.42% (68 runs sampled)
forEach forEach x 5,043,765 ops/sec ±0.60% (67 runs sampled)
for in for in x 9,155,750 ops/sec ±0.50% (68 runs sampled)
for…of for…of x 1,339,234 ops/sec ±0.42% (68 runs sampled)

for...of uses @iterators internally which aren’t as efficient


← Back home