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

  • key holds the name of the current property.
  • object is 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, or for...of instead.

Key Takeaways

  • for...in loops through all enumerable keys of an object.
  • Use object[key] to access each value.
  • Combine with hasOwnProperty() to avoid inherited keys.
  • Avoid using for...in on arrays due to order issues and prototype inheritance.
Next : For Of Loop