for ... of loop
suggest changeconst iterable = [0, 1, 2];
for (const i of iterable) {
console.log(i);
}
Expected output:
0 1 2
The advantages from the for…of loop are:
- This is the most concise, direct syntax yet for looping through array elements
- It avoids all the pitfalls of for…in
- Unlike
forEach(), it works withbreak,continue, andreturninside a function
Support of for…of in other collections
Strings
for...of walks a string by Unicode code point, not by UTF-16 code unit. Each console.log prints one line:
const string = "abc";
for (const chr of string) {
console.log(chr);
}
Expected output:
a b c
Sets
for...of works on Set objects.
Note:
- A Set object will eliminate duplicates.
- A
Setiterates its unique values in insertion order.
const names = ['bob', 'alejandro', 'zandra', 'anna', 'bob'];
const uniqueNames = new Set(names);
for (const name of uniqueNames) {
console.log(name);
}
Expected output:
bob alejandro zandra anna
Maps
for...of also walks a Map. Each step yields a two-element array of key and value.
const map = new Map()
.set('abc', 1)
.set('def', 2)
for (const iteration of map) {
console.log(iteration) //will log ['abc', 1] and then ['def', 2]
}
Destructuring can name the key and the value:
const map = new Map()
.set('abc', 1)
.set('def', 2)
for (const [key, value] of map) {
console.log(key + ' is mapped to ' + value)
}
/*Logs:
abc is mapped to 1
def is mapped to 2
*/
Objects
for...of does not walk a plain object's properties. Use for...in or Object.keys():
const someObject = { name: 'Mike' };
for (const key of Object.keys(someObject)) {
console.log(key + ": " + someObject[key]);
}
Expected output:
name: Mike
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents