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

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2 Solution

Sum Tsui
seal-mask
.a{fill-rule:evenodd;}techdegree
Sum Tsui
Full Stack JavaScript Techdegree Student 29,117 Points

I tried to use the for in loop with a condition but..

var student;
var allProp;

function print(message) {
    var idOutput = document.getElementById('output');
    idOutput.innerHTML = message;
}

for (i = 0; i < students.length; i += 1) {
    student = students[i];
    for (var prop in student) {
        if (prop === 'name') {
            allProp += '<h2>' + 'Student: ' + student.name + '</h2>';
        } else {
            allProp += '<p>' + prop + ': ' + student[prop] + '</p>';
        }
    }
}

print(allProp);

but the output to the page is a bit strange

it has an "undefined" before the first student like this:

undefined

Student: Dave

track: Front End Development

achievements: 158

points: 14730

Samuel Webb
Samuel Webb
25,370 Points

Hey Sum,

I edited your question to the proper markdown syntax for showing code. Make sure you use 3 back ticks(```). That's the same button which has the tilda(~). You were originally using single quotes('''). For more information on formatting in markdown, click the Markdown Cheatsheet located at the bottom of the comment and answer boxes.

2 Answers

Samuel Webb
Samuel Webb
25,370 Points

When you originally set allProp, you're setting it without a value which in turn makes it undefined. When you += a string to an undefined variable type, it seems to convert undefined to a string before concatenating them together. If you make allProp an empty string at the beginning, you shouldn't get the problem anymore.

var student;
var allProp = '';
Ryan Burke
Ryan Burke
1,419 Points

I took the same approach as Sum. I did not even consider the solution in the video as I was putting this together.

Is there a reason why we should not have done it like this? This seems like more fluid logic to me - as you loop through the objects in the array, loop through the keys in the objects, and execute as directed.