Advertisement

Google Ad Slot: content-top

JS For In


The for...in loop is used to iterate over the enumerable properties of an object or an array. It loops through the keys (or property names) of an object.


Syntax:

for (key in object) { 
  // Code to execute for each key 
}


  • key: A variable representing the current key in the iteration.
  • object: The object (or array) whose enumerable properties you want to loop through.
Iterating Over an Object
let user = {
name: "Alice",
age: 25,
city: "New York"
};

for (let key in user) {
console.log(`${key}: ${user[key]}`);
}
Try it yourself

Iterating Over an Array:

Although it's not the best practice to use for...in with arrays (use for or for...of instead), it is possible because arrays in JavaScript are also objects.

Example
let colors = ["Red", "Green", "Blue"];

for (let index in colors) {
console.log(`${index}: ${colors[index]}`);
}
Try it yourself

Iterating Over a String:

You can use for...in to loop through the indices of a string.

Example
let str = "hello";

for (let index in str) {
console.log(`${index}: ${str[index]}`);
}
Try it yourself