How to loop over JavaScript arrays and objects

Published: | Updated: | by Julian Knight Reading time ~2 min.
📖 Kb | 📎 Development | 🔖 JavaScript, ECMAscript

JavaScript can be a pain at times. Loops are a fundamental part of all computer languages but in JavaScript, there are some oddities. This post is a summary of the different loop features and when to use them. It is likely to be updated from time-to-time as the standards are still changing.

This is a personal, and incomplete reminder about doing efficient loops in JavaScript.

Of course, you should generally start with whatever is simplest. Generally you should not attempt to optimise too soon.

Arrays 🔗︎

Objects 🔗︎

The old fashioned way still works & is still generally the fastest.

var keys = obj.keys().sort()
for (var i = 0; i < keys.length; i++) {
  console.log(i, obj[keys[i]])
}

Somewhat faster version of the above (the length is not calculated on each loop and prefix iterator is slightly faster than postfix).

var keys = obj.keys().sort()
for (var i = 0, len = keys.length; i < len; ++i) {
    console.log(i, obj[keys[i]])
}

From JS v5, you can use a combination of Object.keys() and Array.prototype.forEach().

Object.keys(obj).forEach(function(key) {
    console.log(key, obj[key])
})

In addition, Object.values(obj) does what you’d expect.

for ... in (MDN) - includes non-own properties.

From JS v6 (ES2015), you can use for...of.

for (const key of Object.keys(obj)) {
    console.log(key, obj[key])
}

In JS v8 (ES2017), Object.entries() was added which avoids having to look up each value in the original object.

Object.entries(obj).forEach(
    ([key, value]) => console.log(key, value)
)

Object.keys() and Object.entries() iterate properties in the same order as a for...in loop. However, they ignore the prototype chain. Only the object’s own enumerable properties are iterated.

References 🔗︎


comments powered by Disqus