JavaScript For In
8 April 2025 | Category: JavaScript
The for...in loop is used to loop through the properties of an object. It gives you the keys (property names), not the values directly.
✅ Syntax
for (let key in object) {
// code to execute
}
keyis a variable that stores each property name (key) during the loop.- You can access the corresponding value using
object[key].
📦 Example: Looping Through an Object
let person = {
name: "John",
age: 25,
city: "New York"
};
for (let key in person) {
console.log(key + ": " + person[key]);
}
Output:
name: John
age: 25
city: New York
🔍 Looping Through an Array (Not Recommended)
You can use for...in with arrays, but it’s not ideal because it returns indexes as strings, and not in order guaranteed.
let colors = ["red", "green", "blue"];
for (let index in colors) {
console.log(index + ": " + colors[index]);
}
Output:
0: red
1: green
2: blue
🔸 Use for...of or for loops for arrays instead (more reliable and readable).
🧠 When to Use for...in
Use for...in when:
- You want to loop over all keys in an object.
- You need both property names and values.
- You don’t care about order (objects are unordered).
⚠️ Tip: Use hasOwnProperty
If you’re looping through an object that inherits properties from a prototype, use .hasOwnProperty() to avoid unexpected keys.
for (let key in object) {
if (object.hasOwnProperty(key)) {
// Safe to use key
}
}
🧾 Summary
| Feature | for...in Loop |
|---|---|
| Used for | Looping through object keys |
| Output | Property names (keys) |
| Use on arrays? | Not recommended |
| Value access | object[key] |