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!

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

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects Using `for in` to Loop Through an Object's Properties

Ryan Sherry
Ryan Sherry
12,449 Points

Why does the print function from previous videos fail to properly print out the information from the object?

When I use the for-in loop to iterate through the person object and print the property values to the page, it does not work. I either get a blank screen or the skill values print out.

It appears that I am doing something wrong and it seems to be related to the print function because it does print to the console when using console.log, as demonstrated in the video:

Here is my code:

var person = { name : 'Sarah', country : 'US', age : 35, treehouseStudent : true, skills : ['JavaScript', 'HTML', 'CSS'] };

function print(message) { var displayHTML = document.getElementById('objectDiv'); displayHTML.innerHTML = message; }

for (var prop in person) { print(person[prop]);; }

Thanks for your help!

2 Answers

Hey Ryan,

The reason why it is only printing the skills property is because skills is the last property in the loop, and your print() function replaces the HTML in "objectDiv" each time it is ran. Since you want it to print all of the information contained, you need to either utilize another variable or add a += inside your print statement. It depends on whether you'd like only the data from that person in the objectDiv, or any data it gathers to be within the objectDiv, respectively.

I would also change the name of the function print() because in Safari, this is a reserved function for printing.

//If you go this route, each time the print function is called
//the data will be added to the objectDiv and not cleared
function print(message) { 
var displayHTML = document.getElementById('objectDiv'); 
//Added += so that data is concatenated
displayHTML.innerHTML += message; 


//If you go this route, only the data in the loop
//is added to the objectDiv, and any further calls
//to the print function will result in data being overwritten
var msg;
for (var prop in person) { 
msg += person[prop];
Ryan Sherry
Ryan Sherry
12,449 Points

Thank you, I appreciate your answer. That makes sense.

Not a problem, Ryan. You're very welcome. Happy Coding!