How to loop over JavaScript arrays and objects

📖 Kb | 📎 Development | 🔖 javascript, ecmascript


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()
  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.

    ([key, value]) => console.log(key, value)

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

References 🔗︎

comments powered by Disqus