JavaScript for...in Loop
Examples
Iterate (loop) over the properties of an object:
const person = {fname:"John", lname:"Doe", age:25};
let text = "";
for (let x in person) {
text += person[x] + " ";
}
Try it Yourself »
let text = "";
for (let x in person) {
text += person[x] + " ";
}
Iterate (loop) over the values of an array:
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let text = "";
for (let x in cars) {
text += cars[x] + " ";
}
Try it Yourself »
let text = "";
for (let x in cars) {
text += cars[x] + " ";
}
More examples below.
Description
The for...in statements combo iterates (loops) over the properties of an object.
The code block inside the loop is executed once for each property.
Note
Do not use for...in to iterate an array if the index order is important. Use a for loop instead.
See Also:
Syntax
for (x in
object) {
code block to be executed
}
code block to be executed
}
Parameters
Parameter
Description
x
Required.
A variable to iterate over the properties.
A variable to iterate over the properties.
object
Required.
The object to be iterated
The object to be iterated
JavaScript Loop Statements
Statement Description
break Breaks out of a loop
continue Skips a value in a loop
while Loops a code block while a condition is true
do...while Loops a code block once, and then while a condition is true
for Loops a code block while a condition is true
for...of Loops the values of any iterable
for...in Loops the properties of an object
More Examples
Iterate over the properties of window.location:
let text = "";
for (let x in location) {
text += x + "
";
}
document.getElementById("demo").innerHTML = text;
Try it Yourself »
for (let x in location) {
text += x + "
";
}
document.getElementById("demo").innerHTML = text;
Browser Support
for...in is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
| Chrome | Edge | Firefox | Safari | Opera |