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

Script only writes a single object to page... not 5

For some reason this only gives me the last object in the array. What am I missing??? Thanks in advance!

let arrayItem;
let result = '';

let students = [
  {
    name: "Mike", 
    track: "IOS", 
    achievements: 5, 
    points: 345
  },
  {
    name: "Steve", 
    track: "JS", 
    achievements: 6, 
    points: 234
  },
  {
    name: "Jay", 
    Ttack: "IOS", 
    achievements: 8, 
    points: 989
  },
  {
    name: "Sally", 
    track: "Python", 
    achievements: 2, 
    points: 123
  },
  {
    name: "Tom", 
    track: "JSON", 
    achievements: 9, 
    points: 3415
  }
];

for (let i = 0; i < students.length; i++) {
  arrayItem = students[i];                   
  result = arrayItem.name + '<br>';          
  result += arrayItem.track + '<br>';         
  result += arrayItem.achievements  + '<br>';
  result += arrayItem.points + '<br>';
}

document.write(result);

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Staff

Hi there, francisobrien ! You're doing great. The problem here is that every time you start a new iteration of that loop, you are taking result and starting it over again from scratch. You should be concatenating on to it through every iteration.

This line:

 result = arrayItem.name + '<br>';  

Should contain concatenation as well like so:

 result += arrayItem.name + '<br>';  

If it's just the equal sign, it's only an assignment operator and everything that was there gets wiped out entirely. That means that the one thing that will show will be whatever was in the last iteration of that loop.

Hope this helps! :sparkles:

Got it. Thanks Jennifer!