For...in
EasyIn plain terms
for...in iterates over enumerable property keys of an object. Returns keys (not values). Avoid using on arrays - use for...of instead. Use hasOwnProperty to skip inherited properties.
What you need to know
- •Iterates object keys
- •Includes inherited (use hasOwnProperty)
- •Returns strings for array indices
Try it yourself
Copy the code below and run it in your browser console or a code editor:
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(key, obj[key]); // a 1, b 2, c 3
}
// Arrays (keys are indices - avoid, use for...of)
const arr = [10, 20, 30];
for (const i in arr) {
console.log(i, arr[i]); // "0" 10, "1" 20, "2" 30
}Learn more
Dive deeper with these trusted resources: