JavaScript for...in Loop
Subject: JavaScript
The for...in loop in JavaScript is used to iterate over the enumerable properties (keys) of an object. It allows you to loop through all property names of an object, one by one. This loop is not recommended for arrays.
Syntax
keyholds the name of the current property.objectis the object whose keys are being looped.
Example 1: Looping Through an Object
Example 2: Nested for...in Loop
Avoiding Inherited Properties
To avoid properties from the prototype chain:
When to Use for...in
- To loop through all property names of an object.
- Ideal for dynamic key-value structures.
- Not suitable for arrays—use
for,forEach, orfor...ofinstead.
Key Takeaways
for...inloops through all enumerable keys of an object.- Use
object[key]to access each value. - Combine with
hasOwnProperty()to avoid inherited keys. - Avoid using
for...inon arrays due to order issues and prototype inheritance.