for...of in JavaScript
This can be used to iterate through any iterable object such as an Array or String:
const str = 'test'; const arr = [1, 2, 3]; for (let value of str) { console.log(value); } // 't\ne\ns\nt\n' for (let value of arr) { console.log(value); } // '1\n2\n3\n'
for...of can also be used over arguments objects or DOM collections. Which reduces the number of implementations to remember with loops in native JavaScript.
Unfortunately, it cannot be used in basic objects without specifying an iterator function for that object (Which requires Symbol support):
const obj = { property2: 'value2', property1: 'value1' } obj[Symbol.iterator] = function() { const self = this; const keys = Object.keys(this).sort(); let index = -1; return { next: function() { index += 1; if (index < keys.length) { return { done: false, value: self[keys[index]] }; } return { done: true }; } } } for (let value of obj) { console.log(value); } // value 1 // value 2
This has the advantage of making looping through an object consistent. It is important since there is no consistent implementation for object order when looping. Some JS environments loop by alphabetical order or properties, others like the Node.js loop below, in order of property creation:
for (let keyName in obj) { console.log(obj[keyName]); } // (Order below depends on your environment) // value 2 // value 1
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/forOf.js













