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
}
PartMeaning
keyA variable that holds one key in each round. You can name it anything.
inThe keyword that means "go through the keys in this object"
objectThe 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

Roundkeystudent[key]
1"name""Rahul"
2"age"21
3"course""B.Tech"
4"city""Pune"
—No more keysLoop 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 get undefined.
  • phone[key] → JavaScript uses the value stored in the variable key, 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 brackets object[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 + 1 gives "01", not 1! 😮
  • 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.

MethodReturnsExample 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).length gives the number of keys instantly:

When to use which?

NeedBest choice
Simple loop over an object's keysfor...in
Only the object's own keys (safe)Object.keys()
Only the valuesObject.values()
Both key and value neatlyObject.entries()
Count the keysObject.keys(obj).length

Common Mistakes to Avoid

MistakeProblemFix
Using obj.key inside the loopGives undefinedUse obj[key]
Using for...in on arraysIndex is a string, extra keys may appearUse for...of
Using for...of on a plain object❌ TypeError: not iterableUse for...in or Object.entries()
Treating keys as numbers"1" + 1 = "11"Convert with Number(key)
Adding or deleting keys inside the loopConfusing resultsOnly change values inside the loop
Forgetting about inherited keysExtra keys appearUse Object.hasOwn() or Object.keys()

Quick Summary Table

TaskCode
Loop through keysfor (const key in obj) { }
Get the valueobj[key]
Only own keysif (Object.hasOwn(obj, key))
Count keysObject.keys(obj).length
Key + value (modern)for (const [k, v] of Object.entries(obj))

Key Takeaways

  • The for...in loop goes through the keys of an object, one by one.
  • Always use object[key] (square brackets) to get the value, not object.key.
  • Keys always come as strings, and number-like keys are listed first, in sorted order.
  • Use for...in for objects, and for...of for arrays and strings.
  • For safer, modern code, use Object.keys(), Object.values(), or Object.entries() with for...of.