Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Lee Cockcroft
5,147 Pointslooping objects in javascript
Hi Guys,
I am trying to write the object as it is, however its only displaying the last property "age".
Could someone explain why please? ps I have a "<div id="output"> </div>" in my code.
var object= { name:"lee", age:31 };
for(prop in object){ document.getElementById("output").innerHTML=prop+object[prop];
}
Thanks Lee
3 Answers
Simon Coates
28,695 PointsYou're setting the value inside the element and then setting it again. This has the effect of overwriting it. Maybe something like:
var object= { name:"lee", age:31 };
for(prop in object){ document.getElementById("output").innerHTML += prop+object[prop];
}
or
var object= { name:"lee", age:31 };
var stringy = "";
for(prop in object){
stringy = stringy +" " +prop + " "+ object[prop];
}
document.getElementById("output").innerHTML =stringy;
Lee Cockcroft
5,147 PointsThanks for your answer,
I can see your last example works the way i want it to,
However, I still dont understand why? I don't see ow i am setting the value twice?
sorry, this may seem a silly question but its just dont sinking in.
Thanks Lee
Jason Anello
Courses Plus Student 94,610 PointsHi Lee,
Whenever you set the innerHTML property to something, it replaces whatever is currently there. It doesn't append to it.
The first time in your loop, you're saying "I want the innerHTML set to the info for the name property."
The second time through the loop, you're saying "Ok, now I want the innerHTML set to the info for the age property."
To do something like this you have to build up the output to what you want.
Simon's first example with the += operator is saying, take what's currently in the innerHTML and add on the current property to it. Then put it back in the innerHTML.
The second example is more efficient because it builds up a string of all the output you want and then writes it out to the dom all at once.
Lee Cockcroft
5,147 PointsThank you Jason, I understand it now.
Thank you for all your help!
Sometimes the obvious needs pointing out :)
Simon Coates
28,695 PointsSimon Coates
28,695 PointsJason Anello's explanation is very concise. THe basic fact is that = sets the left hand side to the content of the right (and nothing else) - so your div had the contents of the last assignment statement (the bit with =). += sets the left hand side to itself plus the right hand side.