Get AI Code Completions for Your IDE

Home   >   Tutorials   >   JavaScript   >   How to Use the for…in Statement in JavaScript

JavaScript - How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties.

Basic for…in loop example

The following code demonstrates a basic example using the for…in statement to loop through the properties of an object.

const scores = { Danny: 12, Michelle: 16, Tim: 7, Naomi: 13, Dwyane: 10 };
for (const player in scores) {
    console.log(`${player }` + ' scored ' + `${scores[player]}` + ' points');
}
// Expected output:
// Danny scored 12 points
// Michelle scored 16 points
// Tim scored 7 points
// Naomi scored 13 points
// Dwyane scored 10 points

In the above example the object scores holds a list of players’ names and their associated scores as key: value pairs.

The for…in statement iterates over the scores object and prints each name, along with its score, to the console. Each entry is assigned to the variable player in turn, which is then used to print the data to the console.

Note that the name player is not important, though, and could be replaced with any other valid variable name. For readability purposes, you should use a variable name that refers to the meaning of the object’s keys whenever possible.

Syntax

The syntax of the for…in statement is as follows:

for (variable in object) {

function or code block for execution

}

variable: as the loop iterates over the object’s properties, the property values are stored in this variable.

object: the object to be iterated over.

In the example above, the variable element was named player as it iterated over the list players (we could have just as easily called the variable x, if we desired). The object to iterate over is scores. For each of the key:value pairs in the scores object, a console.log() method is executed.

Note: for…in statement loop through an object’s keys in arbitrary order!!

This means that the order in which properties are handled by the loop may not correlate with the order of appearance of those properties in the original object. Due to this behavior, it is not recommended to use for…in with Arrays – especially if the order in which elements are processed is important. Arrays have their own iteration methods that should be used instead.

Note: the for…in statement does not iterate over non-enumerable properties, nor does it iterate over Symbols!

Other frequently used loops

There are several other types of loop statements in JavaScript that can be used in addition to for…in statements. These include:

  • for statement
  • for…of statement
  • do…while statement
  • while statement
  • various iteration methods for JavaScript Arrays.

 

Related Articles

JavaScript – How to Use for Statements

JavaScript – How to use the for…of Statement

JavaScript – How to Use The Array forEach() Method

Get AI Code Completions for Your IDE