The for...in Loop
The for...in loop iterates over the enumerable properties of an object.
It is typically used for iterating over object keys.
eg:
let person = { name: "Saran", age: 22 };
for (let key in person) {
console.log(key, ":", person[key]);
}
for...of loop
Used to iterate over arrays, strings, or iterable objects.
let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
Top comments (1)
I particularly appreciated the distinction made between the
for...inloop, which iterates over object properties, and thefor...ofloop, which is better suited for arrays and other iterable objects. The example with thepersonobject usingfor...into log key-value pairs is a clear illustration of its use case. In my experience, understanding the difference between these two loops has helped avoid unintended iterations over inherited properties or unexpected behavior with arrays. What considerations should be taken when deciding between these loops for iterating over complex data structures, such as nested objects or arrays of objects?