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

Paul Costanza
Paul Costanza
4,173 Points

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
203,717 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>'
Paul Costanza
Paul Costanza
4,173 Points

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