For...in Loops
When you are using an object as a dictionary or hash map, you often need to iterate over all the properties stored inside it. The for...in loop is specifically designed to iterate over the keys of an object.
The Syntax
const user = {
name: "Eren",
role: "Admin",
age: 19,
};
// "key" becomes the string name of the property in each iteration
for (const key in user) {
// Use bracket notation to dynamically access the value
console.log(`${key}: ${user[key]}`);
}
// Output:
// name: Eren
// role: Admin
// age: 19
A Note on Traversal Order
Modern JavaScript specifications do guarantee a specific iteration order for for...in loops:
- Integer-like keys (those that can be array indices) are sorted first in ascending order.
- All other string keys follow in chronological order of creation.
However, relying on object key order in your logic is heavily discouraged because it can be confusing to read. If you strictly require sequential order, you should extract the keys into an Array and sort them manually (we will cover Arrays in a later chapter).
Practical Example
A common use case for for...in is filtering an object’s properties based on a specific prefix.
function logMatchingProperties(logObj, prefix) {
for (const key in logObj) {
if (key.startsWith(prefix)) {
console.log(`Found: ${key} -> ${logObj[key]}`);
}
}
}
const entry = {
msgId: "abc123",
msgText: "Order shipped",
timestamp: "2025"
};
logMatchingProperties(entry, "msg");
// Output:
// Found: msgId -> abc123
// Found: msgText -> Order shipped