Iterate Keys
for...in iterates over enumerable keys of an object.
It is best suited for objects, not arrays.
JavaScript Tutorial
The for...in loop iterates over the keys of an object.
It is useful for inspecting properties or building key-based logic.
Object iteration is common for configuration, settings, and dynamic data shapes.
Knowing how for...in behaves helps you avoid inherited keys and ordering surprises.
for (const key in object) { ... }const user = { id: 1, name: "Ava" };
for (const key in user) {
console.log(key, user[key]);
}Iterate keys and access values by bracket notation.
const obj = Object.create({ inherited: true });
obj.own = "yes";
for (const key in obj) {
if (Object.hasOwn(obj, key)) {
console.log(key);
}
}Filter out inherited keys with Object.hasOwn.
for...in iterates over enumerable keys of an object.
It is best suited for objects, not arrays.
for...in also iterates over inherited properties unless filtered.
Use Object.hasOwn() or Object.prototype.hasOwnProperty.call() to filter.
Do not rely on key order when using for...in.
If you need order, use Object.keys and sort explicitly.
const settings = { theme: "dark", compact: true };
Object.keys(settings).forEach((key) => {
console.log(key, settings[key]);
});Use Object.keys for more explicit control.
const list = ["a", "b"];
for (const key in list) {
console.log(key); // indexes as strings
}Use for...of for array values instead.
Without
const obj = { a: 1, b: 2 };
for (let i = 0; i < Object.keys(obj).length; i++) {
const key = Object.keys(obj)[i];
console.log(key, obj[key]);
}With
const obj = { a: 1, b: 2 };
for (const key in obj) {
console.log(key, obj[key]);
}Use for...of or array methods for values.
Filter with Object.hasOwn when needed.
Do not rely on key order unless you sort explicitly.
It iterates over enumerable keys of an object.
Filter with Object.hasOwn.
for...of gives values directly and avoids key surprises.
Practice: Iterate over a settings object and log key=value pairs.
const settings = { theme: "light", layout: "grid" };
// TODO: log each key and value
One Possible Solution
const settings = { theme: "light", layout: "grid" };
for (const key in settings) {
console.log(key, settings[key]);
}Enumerable keys of an object, including inherited ones unless filtered.
It iterates keys as strings and can include unexpected properties.
Use Object.hasOwn(obj, key).
Try adding more keys and see how for...in iterates them.