The for...in loop

How to do the for...in loop to loop through object properties! Tutorial brought to you by EasyProgramming.net

by von

HTML

<!-- JavaScript Objects - The for...in loop #41 -->
<p>
Welcome to the 41st Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. We're not quite done with loops yet, we have one more left. The <code>for...in</code> loop! This loop allows you to loop through the properties of an object, kind of like how you can loop through each item in an array using the <code>forEach()</code> loop.
</p>
<p>
This is extremely useful when you want to iterate through an object and can come in handly when you want to parse JSON into an even more readable format (such as a table). 
</p>

<h2>
Syntax of a <code>for...in</code> loop:</h2>

<p>
<code><pre>
for(property in object){
    //E.g. object - person = {name:"Nazmus"};
    var x = property; //name of the property itself - name
    var y = object[property]; //value of the property - Nazmus
}
  </pre>
</code>
</p>

<p>
<h2>
Let's practice:</h2>
<span id="output"></span>
<br /><br />

JavaScript

var person = {
		name: 'Nazmus',
    city: 'Boston',
    state: 'Massachusetts',
    website: 'EasyProgramming.net',
    language: 'JavaScript',
    job: 'Developer',
    hair: 'Black',
    eyes: 'Brown',
    hands: 'Two'
}

var output = document.getElementById("output");

for(p in person){
		output.innerHTML += p + ': ' + person[p] + "<br />";
}