HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Loop For In

The for...in statement loops through the properties (keys) of an Object. It is designed specifically for objects, not arrays.


Object Iteration Syntax

In each iteration, one property (key) of the object is assigned to the variable.

for (key in object) {
  // code block to be executed
}

Case Study: Looping over an Object

const person = { fname: "Mim", lname: "Akter", age: 22 };

let text = "";
for (let x in person) {
  text += person[x] + " "; // Accessing the value using the key
}
// Result: Mim Akter 22

Looping over Arrays with For In

You can use for...in over an array, but it is generally avoided. It iterates over the array indexes (0, 1, 2) instead of the values.

Why you should avoid it for arrays:
  • The order of iteration is not always guaranteed.
  • It treats indexes as strings ("0", "1"), which can lead to mathematical errors.
  • It also iterates over user-defined properties if they are added to the array prototype.

Array.forEach() Alternative

For arrays, a cleaner and more modern approach is forEach():

const numbers = [45, 4, 9, 16, 25];

numbers.forEach(function(value) {
  console.log(value);
});

Key Points to Remember

  • for...in is for iterating over Object properties
  • The loop variable represents the key (property name)
  • Use the bracket notation object[key] to get the property value
  • Avoid using for...in for Arrays where order is important
  • It inherited "enumerable" properties from the prototype chain
  • Best used for debugging or simple object data extraction