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


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.