- for...in iterates over the enumerable properties of an object
- for...of iterates over the property values of objects
let myString = "test";
// logs 0, 1, 2, 3
for (let i in myString) {
console.log(i);
}
// logs t, e, s, t
for (let i of myString) {
console.log(i);
}
- for...in should not be used if the index order of the items is important because there is no guarantee they will be given in the intended order
- If you only want to iterate over an object's own properties, use getOwnPropertyNames() or something similar, instead of for...in.
- You can use const as the variable for either loop, as long as you're not trying to change the value of the variable (thus obeying the rules of const)
- You can use statements like break or return to terminate either of these loops before they complete