For Of Loops
The for...of
statement creates a loop that iterates over iterable objects (Array
, Map
, Set
, arguments
, etc.). for...of
is particularly useful for iterating over other kinds of collections. cannot iterate over objects, so for...in
provides the best way to iterate over an object. For of loops were introduced in ES6. They're excellent for iterating over arrays.
For in versus For of
For in loops are best used to iterate over objects, where for of loops are great for iterating over arrays. Take the below example. I want an array of cat names, and I want to console each name and "says meow". If I try and do it in a for in loop, I won't get what I'm looking for. Take the below code.
// cat example
var catArray = ['tabby', 'british shorthair', 'burmese', 'maine coon', 'rag doll'];
for (var cat in catArray){
console.log(cat, 'says meow');
}
// this results in 0 says meow
// 1 says meow
// 2 says meow
// 3 says meow
// 4 says meow
Notice that using a for...in
loop results in the keys being printed out. So the array indexes, or keys are printed instead of the value we want.
// cat example
var catArray = ['tabby', 'british shorthair', 'burmese', 'maine coon', 'rag doll'];
for (var cat of catArray){
console.log(cat, 'says meow');
}
// this results in:
// tabby says meow
// british shorthair says meow
// burmese says meow
// maine coon says meow
// rag doll says meow
When we use for...of
, we get the value of the items in our array printed out. This is usually what you want when iterating over an array, so for now keep in your mind that "for of" is useful for things like arrays, and "for in" is useful for objects.
// for of loops
for (var i /*variable section*/ of obj /*object section*/) {
console.log(i) /*statement*/
}
// Practice
var array1 = [3,5,7];
// For In Loop - note that it only logs out the KEYs in the key/value pairs
for (var a in array1) {
console.log(a); // '0', '1', '2'
}
// For Of Loop - it logs the values
for (var a of array1) {
console.log(a); // '3', '5', '7'
}
Last updated