🔍

Understanding JavaScript `for...in` Loop

May 15, 2025

JavaScript for...in Loop

Overview

  • Purpose: Iterates over the enumerable properties of an object.
  • Use Case: Allows accessing each property name and its corresponding value.

How to Use for...in Loop

  1. Define an Object

    • Example: developer object with keys and values.
  2. Syntax:

    • Use for...in loop to iterate over object properties.
    for (let key in developer) { // Code to execute }
    • key: Represents the property name.
    • developer: The object being iterated.
  3. Logging Property Names

    • Use console.log(key) inside the loop to log all property names.
    • Example Output: name, age, city.
  4. Logging Property Values

    • Access property values using bracket notation: developer[key].
    • Note: Do not use dot notation (developer.key) as it returns undefined.
    • Example Output: Amy, 27, London.

Example Scenario

  • Script Example:
    • Object Definition: Define developer object.
    • Loop Implementation: for (let key in developer) { console.log(`${key}: ${developer[key]}`); }
    • Expected Output:
      • Logs property names and values in the format name: Amy, age: 27, city: London.

Conclusion

  • Next Steps: Storing objects in an array.
  • Engagement: Encouragement to comment, like, share, and subscribe for more content.

These notes capture the key points from the lesson on using the for...in loop in JavaScript for iterating over object properties and accessing their values.