JavaScript for/in statement

Definition and usage

The for/in statement loops through the properties of an object.

The code block inside the loop will be executed once for each property.

JavaScript supports different types of loops:

  • for - Loop the code block multiple times
  • for/in - Loop through the properties of an object
  • for/of - Loop through the values of an iterable object
  • while - Loop the code block while the specified condition is true
  • do/while - Execute the code block once, then repeat the loop if the specified condition is true

Note:Do not use the for/in statement to loop through arrays where the index order is important. Use the for statement instead.

Example

Loop through the properties of the object:

var person = {fname:"Bill", lname:"Gates", age:25}; 
var text = "";
var x;
for (x in person) {
  text += person[x] + " ";
}

Try it yourself

Syntax

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

Parameter value

Parameter Description
var Required. The variable for iterating object properties.
object Required. The specified object to be iterated.

Technical details

JavaScript version: ECMAScript 1

Webbläsarstöd

Sats Chrome IE Firefox Safari Opera
for/in Stöd Stöd Stöd Stöd Stöd

Relaterade sidor

JavaScript-handbok:JavaScript For-slinga

JavaScript referenshandbok:JavaScript for-sats