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

Different approach using the `for in` loop

https://w.trhou.se/hhkr8yw0ck

I used the for in loop inside of the for loop to list all of the properties and values. Then I used an if statement to differentiate student names(h2) and the other properties(p). Please let me know if I am able to shorten/clean my code up. Thank you!

1 Answer

Steven Parker
Steven Parker
231,269 Points

Be aware that there will be some behavioral differences with this approach:

  • a missing property will be silently omitted (the video code will indicate "undefined")
  • an extra property will be included (the video code only prints the specific ones)
  • the order in which the properties are listed isn't guaranteed

And one obvious code reduction:

      if (prop === "name") {
        list += '<h2>Name: ' + students[i].name + '</h2>'

Oh wow, thanks man! Much appreciated.

Mohamad Faiz Khairi Mohd Nazri
Mohamad Faiz Khairi Mohd Nazri
5,668 Points

using '<h2>Name: ' instead of prop will make the code longer because we need to write else if for every prop name

My solution:

if (prop === 'name') {
  list += '<h2>' + prop + ': ' + students[i][prop] + '</h2>'
} else {
  list += '<p>' + prop + ': ' + students[i][prop] + '</p>'
}

The downside of it is the property name display on browser is not capitalize on the first letter