for...in Loop
Imagine you get a new Aadhaar card 🪪 and want to read all its details:
- Name: Priya Sharma
- Date of Birth: 12-05-2001
- Gender: Female
- Address: Lucknow
Each detail has a label (like "Name") and a value (like "Priya Sharma"). You read it label by label, from top to bottom.
In JavaScript, this kind of information is stored in an object:
let aadhaar = {
name: "Priya Sharma",
dob: "12-05-2001",
gender: "Female",
address: "Lucknow"
};
Now, how do we go through every label in this object one by one? A normal for loop needs index numbers like 0, 1, 2, but objects don't have index numbers. They have keys.
For this job, JavaScript gives us the for...in loop.
What Is a for...in Loop?
A for...in loop goes through all the keys (property names) of an object, one at a time.
- Key = the label (like
name,age) - Value = the data stored for that label (like
"Priya",21)
The for...in loop gives you the key, and you use the key to get the value.
Syntax
for (const key in object) {
// key → the property name
// object[key] → the value
}
| Part | Meaning |
|---|---|
key | A variable that holds one key in each round. You can name it anything. |
in | The keyword that means "go through the keys in this object" |
object | The object you want to loop through |
object[key] | Gets the value of the current key |
Your First for...in Loop
How It Works, Step by Step
| Round | key | student[key] |
|---|---|---|
| 1 | "name" | "Rahul" |
| 2 | "age" | 21 |
| 3 | "course" | "B.Tech" |
| 4 | "city" | "Pune" |
| — | No more keys | Loop stops |
The loop automatically stops after the last key. You don't need a counter or a condition.
Why object[key] and Not object.key?
This is the most common beginner mistake with for...in.
Why does this happen?
phone.key→ JavaScript looks for a property whose name is literally "key". It doesn't exist, so you getundefined.phone[key]→ JavaScript uses the value stored in the variablekey, like"brand"or"price". ✅
Think of it like a locker room 🔐:
phone.key→ "Open the locker labelled KEY." There is no such locker!phone[key]→ "Open the locker whose name is written on this slip." Correct!
Rule: Inside
for...in, always use square bracketsobject[key].
Real-Life Examples
Example 1: Restaurant menu 🍽️
Example 2: Calculating total marks 📊
Example 3: Finding the highest-scoring subject 🏆
Example 4: Counting the keys in an object
Changing Values Inside for...in
You can update the values of an object while looping.
Example: a 10% price hike on all items 📈
Example: converting all names to uppercase
Tip: Changing values is safe. But adding or deleting keys while looping can cause confusing results, so avoid it.
Using if, break, and continue Inside for...in
All the tools you learned earlier work inside for...in.
Filtering with if
Stopping early with break
Skipping with continue
Looping Through Nested Objects
Objects can have other objects inside them. You can use a for...in inside another for...in.
The Order of Keys
for...in usually goes through keys in the order they were added. But there is one special rule:
Keys that look like whole numbers come first, sorted from smallest to largest. Other keys follow in the order they were added.
Notice that 1 and 2 came first (sorted), and then b and a in the order they were written.
Key point: If the order is very important, don't depend only on the object. Use an array instead.
Keys Are Always Strings
Every key in for...in comes as a string, even if it looks like a number.
If you need a number, convert it: Number(roll).
⚠️ Inherited Properties
Objects in JavaScript can inherit properties from a "parent" object. for...in also shows these inherited keys, not just the object's own keys.
Don't worry: For normal objects created with
{ }, you won't usually face this problem. Just remember it exists when you learn about inheritance later.
⚠️ Avoid for...in with Arrays
for...in can loop over arrays, but it is not recommended.
Problems:
- The index comes back as a string, not a number. So
index + 1gives"01", not1! 😮 - It may also show extra properties added to the array.
- The order is not guaranteed in every situation.
✅ For arrays, use for...of or a normal for loop instead:
Easy trick:
in→ keys in an object.of→ values of an array.
for...in with Strings
for...in also works with strings, giving the position of each character (as a string).
But just like arrays, for...of is better for strings.
Modern Alternatives: Object.keys(), Object.values(), Object.entries()
JavaScript also gives us methods that turn an object into an array, which you can then loop through with for...of.
| Method | Returns | Example result |
|---|---|---|
Object.keys(obj) | An array of keys | ["name", "age"] |
Object.values(obj) | An array of values | ["Rahul", 21] |
Object.entries(obj) | An array of key, value pairs | [["name","Rahul"], ["age",21]] |
Bonus benefits:
- These methods show only the object's own keys, with no inherited ones.
Object.keys(car).lengthgives the number of keys instantly:
When to use which?
| Need | Best choice |
|---|---|
| Simple loop over an object's keys | for...in |
| Only the object's own keys (safe) | Object.keys() |
| Only the values | Object.values() |
| Both key and value neatly | Object.entries() |
| Count the keys | Object.keys(obj).length |
Common Mistakes to Avoid
| Mistake | Problem | Fix |
|---|---|---|
Using obj.key inside the loop | Gives undefined | Use obj[key] |
Using for...in on arrays | Index is a string, extra keys may appear | Use for...of |
Using for...of on a plain object | ❌ TypeError: not iterable | Use for...in or Object.entries() |
| Treating keys as numbers | "1" + 1 = "11" | Convert with Number(key) |
| Adding or deleting keys inside the loop | Confusing results | Only change values inside the loop |
| Forgetting about inherited keys | Extra keys appear | Use Object.hasOwn() or Object.keys() |
Quick Summary Table
| Task | Code |
|---|---|
| Loop through keys | for (const key in obj) { } |
| Get the value | obj[key] |
| Only own keys | if (Object.hasOwn(obj, key)) |
| Count keys | Object.keys(obj).length |
| Key + value (modern) | for (const [k, v] of Object.entries(obj)) |
Key Takeaways
- The
for...inloop goes through the keys of an object, one by one. - Always use
object[key](square brackets) to get the value, notobject.key. - Keys always come as strings, and number-like keys are listed first, in sorted order.
- Use
for...infor objects, andfor...offor arrays and strings. - For safer, modern code, use
Object.keys(),Object.values(), orObject.entries()withfor...of.