Introduction to For...in Loops
You'll learn how to use for...in loops to iterate over an object's property keys.
What Is a For...in Loop?
A for...in loop is specifically designed to enumerate the keys (property names) of an object. While for...of iterates over values in iterable structures like arrays and strings, for...in focuses on property names in objects.
Think of it like getting a list of all the labels on file folders in a cabinet—you're seeing the names of what's inside, not the contents themselves.
Basic Syntax
for (let key in object) {
// code that uses key
}
The loop variable (key in this example) receives each property name as a string, one at a time.
Simple Example
const person = {
name: "Alice",
age: 28,
city: "Boston"
};
for (let key in person) {
console.log(key); // Logs: "name", "age", "city"
}
Notice that we're getting the keys ("name", "age", "city"), not the values themselves. To access the actual values, you'd use person[key]:
for (let key in person) {
console.log(key + ": " + person[key]);
// Logs: "name: Alice", "age: 28", "city: Boston"
}
Why For...in for Objects?
Objects don't have a built-in iteration protocol like arrays do, so for...of won't work directly on plain objects. The for...in loop gives you a way to walk through all the keys, which you can then use to access corresponding values.
Key Takeaway: for...in loops iterate over object property keys (as strings), making them ideal for enumerating an object's properties.