Back to course

Iterating Object Properties with 'for...in'

JavaScript: The Complete '0 to Hero' Beginner Course

67. Iterating Object Properties: for...in

The for...in loop is specifically designed to iterate over the keys (property names) of an object.

Syntax

javascript for (const key in objectName) { // key holds the property name (string) // objectName[key] accesses the property value }

Example

javascript const product = { id: 'P102', name: 'Keyboard', price: 45.99, stock: 100 };

for (const prop in product) { console.log(${prop}: ${product[prop]}); }

// Output: // id: P102 // name: Keyboard // price: 45.99 // stock: 100

Caution with for...in

for...in can sometimes iterate over inherited properties (from the object's prototype chain). For modern iteration, it is often safer to use Object.keys() or Object.entries() (Lesson 68), especially for complex object interaction.