Iterating over a DOM collection

Iterating over DOM collections like NodeList: the following example adds a read class to paragraphs that are direct descendants of an article:

// Note: This will only work in platforms that have
// implemented NodeList.prototype[Symbol.iterator]
let articleParagraphs = document.querySelectorAll('article > p');
for (let paragraph of articleParagraphs) {
paragraph.classList.add('read');
}

Closing iterators

In for...of loops, abrupt iteration termination can be caused by break, continue[4], throw or return[5]. In these cases, the iterator is closed.

Do not reuse generators

Generators should not be re-used, even if the for...of loop is terminated early, for example via the break keyword. Upon exiting a loop, the generator is closed and trying to iterate over it again does not yield any further results.

This loop logs only enumerable properties of iterable object, in original insertion order. It doesn't log array elements3, 5, 7 or hello because those are not enumerable properties. But it logs array indexes as well as arrCustom and objCustom, which are. If you're not sure why the properties are iterated over, there's a more thorough explanation of how array iteration and for...in work.

This loop is similar to the first one, but it uses hasOwnProperty() to check, if the found enumerable property is object's own (not inherited). And if it is, the property is logged. Properties 0, 1, 2 and foo are logged because they are own properties (not inherited). Properties arrCustom and objCustom are not logged because they are inherited.

for (let i of iterable) {
console.log(i); // logs 3, 5, 7
}

This loop iterates and logs values that iterable as an iterable objectdefines to be iterated over, which are array elements 3, 5, 7 and not any of object's properties.