Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

for…in loop – JavaScript

Length: 10 minutes

Summary

const person = { name: "John", age: 21, job: "Developer" };

for (const property in person) {
  console.log(property + ": " + person[property]);
}

Details

The for…in loop can be used to iterate over the properties in an object.

To write a for…in loop, you need an object to use. In this example we created an object called person. Then, write the for keyword followed by a pair of parentheses and curly braces:

const person = { name: "John", age: 21, job: "Developer" };

for () {

}

Then, declare a constant or variable inside the parentheses. You can name it whatever you want. In this example, we’re calling it property.

const person = { name: "John", age: 21, job: "Developer" };

for (const property) {

}

Then, add the in keyword and the name of an object.

const person = { name: "John", age: 21, job: "Developer" };

for (const property in person) {

}

Then, use the variable name you created before inside the for…in loop to access the current property in the object.

const person = { name: "John", age: 21, job: "Developer" };

for (const property in person) {
  console.log(property + ": " + person[property]);
}

Demo

Exercises

Try the following statements in the console:

const person = { name: "John", age: 21, job: "Developer" };

for (const property in person) {
  console.log(property + ": " + person[property]);
}

You should see each property and value print out to the console.

Back to: JavaScript Reference > JS Loops