DEV Community

vishwa v
vishwa v

Posted on • Edited on

javascript(method-1)

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]);
}

Enter fullscreen mode Exit fullscreen mode

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);
}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
topstar_ai profile image
Luis Cruz

I particularly appreciated the distinction made between the for...in loop, which iterates over object properties, and the for...of loop, which is better suited for arrays and other iterable objects. The example with the person object using for...in to 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?