The for...of statement loops through the values of an iterable
object. It works for built-in iterables like Arrays, Strings, Maps, NodeLists, and more.
In each iteration, the value of the next property is assigned to the variable.
for (variable of iterable) {
// code block to be executed
}
Unlike for...in, this gives you the actual values directly.
const cars = ["BMW", "Volvo", "Saab"];
for (let x of cars) {
console.log(x); // BMW, Volvo, Saab
}
You can use for...of to loop over each character in a string.
let language = "JavaScript";
for (let x of language) {
console.log(x); // J, a, v, a, s, c, r, i, p, t
}
Understanding the difference between these two loops is critical for writing clean JavaScript:
for...in iterates over the property names
(keys).for...of iterates over the property
values (data).for...in for Objects. Use
for...of for Arrays, Strings, and Sets/Maps.
for...of is for iterating over iterable
valuesfor loop
for...in for those)