The for loop in JavaScript is the most flexible, but not the most convenient loop. To use it to iterate over all elements of the iterated object, we need to set the counter, the rules for changing it, and the conditions for stopping. In JavaScript, there is a higher-level for…of loop to iterate over iterable objects. It allows us to avoid writing extra code. The code in this case has similar functionality, but it turns out cleaner and more readable.
Iterating with For…of
The for…of statement loops through iterable loops. It iterates over each element of the iterable object and executes the body of the loop. Iterable objects in JavaScript are Array, Set, Map, String, and so on.
For…of loop, when iterating over an iterable object, allows us not to think about anything other than the body of the loop and not write extra code. But it's a highly specialized loop. For example, if we need to loop through an array in reverse order, starting from the last element, then the for...of loop will not work for us. Also, the for...of loop won't do if we need to iterate over not every element of the array but, for example, every second one, because the for...of loop iterates over each element.
Iterating over an Array and String
Since an array is a classic example of an iterable object, we can iterate over it with a for…of loop.
const carsList = ['Bmw', 'Pejo', 'Ferrari'];
for (const car of carsList) {
console.log(car);
}
// 'Bmw'
// 'Pejo'
// 'Ferrari'The for...of loop needs to be handled with care, just like any other loop. We can mistakenly get into an infinite loop since iteration with for...of loop happens "live". This means that any changes we make to the iterable can affect its outcome.
// we get an error or an infinite loop
const myArray = [1,2,3];
for(let item of myArray) {
myArray.push('new');
}A string is an iterable object. While not obvious, a string is not much different from an array in JavaScript. For a for…of loop, a string is the same array with ordered elements, the elements of which are its letters.
const word = "code";
for (const letter of word) {
console.log(letter);
}
// "c"
// "o"
// "d"
// "e"Iteration over a Set and Map
A built-in set object is also iterable. When iterating over a set, the body of the loop is executed once for each element.
const cart = new Set(['Milk', 'Cheese', 'Carrot']);
for (const food of cart) {
console.log(food);
}
// 'Milk'
// 'Cheese'
// 'Carrot'A built-in map object is an iterable object in JavaScript. A map is iterated over key/value pairs. So each time the iterator returns an array where the first element is the key and the second is the value.
const wears = new Map([["T-short", 'XL'], ["Cap", 'L'], ["Shoes", '42']]);
for (const [key, value] of map) {
console.log(key, value);
}
// 'T-short' 'XL'
// 'Cap' 'L'
// 'Shoes' '42'Iterating over arguments in functions
The arguments object in functions is also an iterable object.
function myFunc() {
for (let arg of arguments) {
console.log(arg);
}
}
myFunc('Chemistry', 'English', 'Mathematics');
// Chemistry
// English
// MathematicsIterating over an object with for...of
In JavaScript, by default, an object is not iterable. An object of the class object is not iterable. If we try to iterate over it with the for…of loop, we'll get an error.
If we need to iterate over the properties of an object, then for these purposes we can use the for…in loop specially designed for this. However, if for some reason it is mandatory to use for…of to iterate over an object, then for…of should be used with the Object.entries() method. Object.entries() returns an array of the object's keys and the object`s values. With the help of destructuring assignment, we can access this array.
const obj = { a: 1, b: 2, c: 3 };
//if we need only keys
for (const key of Object.keys(obj)) {
console.log(key);
}
//if we need only values
for (const value of Object.values(obj)) {
console.log(value);
}
//if we need keys and values both
for (const [key, value] of Object.entries(obj)) {
console.log(key, value);
}Break and continue
The break and continue statements in for…of loops work exactly the same way as they do in the for loop. So with break we can exit the loop.
const arr = [1, 2, 3, 4, 5];
for (const element of arr) {
if (element === 4) {
break;
}
console.log(element);
}
// 1
// 2
// 3With continue we can skip the iteration.
const arr = [1, 2, 3];
for (const element of arr) {
if (element === 2) {
continue;
}
console.log(element);
}
// 1
// 3Conclusion
The for…of loop is a highly specialized loop for iterating over such iterable objects as array, set, map, string, and so on. The for…of loop executes the body of the loop for each element of the iterable and ends iterating over it at the last element. If we try to iterate over an object with the for…of loop, we'll get an error, but by turning the object into an array with Object.keys(), Object.values(), or Object.entries() we can iterate over it. We can skip one iteration of the for…of loop with continue or break it with break, just like in the for loop.