JavaScript for…in loop in action

Ever tired of using traditional for loop? Try for…in loop :)

Pavan Chilukuri
Nov 11, 2018 · 2 min read
Image for post
Image for post

for...in loop iterates over the properties of an object. It returns a list of keys on the object being iterated. It eliminates the counting logic as in the traditional for loop.

Syntax

for (variable in object) { ...
}

Let’s say we have a JSON object in the below format — all the keys have an array of objects as values.

let employees = {
"5": [{
"id": 35,
"job": "Front end developer",
"description": "based in Ohio"
},
{
"id": 36,
"job": "Java developer",
"description": "based in Seattle"
}
],
"6": [{
"id": 4,
"job": "UI Developer",
"description": "based in NJ"
},
{
"id": 5,
"job": "Angular developer",
"description": "based in NY"
}
]
}

Iterating over the JSON object,employees

for (let i in employees) {
for (let j in employees[i]) {
console.log(employees[i][j].job);
}
}

Output from the browser console

Image for post
Image for post

You may check out the source code in Codepen.


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store