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

Eliana Haig
Eliana Haig
4,239 Points

Message Printing Too Many Times

I can't figure out why my code is printing the objects in the array multiple times. What's wrong with my code? Guessing it's something to do with how I coded one of the loops. Thanks for your help! Here's the code. https://w.trhou.se/vo17pjzb0r

2 Answers

Pieter Bracke
Pieter Bracke
4,078 Points

When you use the for (prop in students){} It is going to loop the complete var students times the number of students there are in the var students you don't really need it here ... I made a little codepen to show you the solution. I commented out the parts you don't need :)

https://codepen.io/anon/pen/dVRKRm

Eliana Haig
Eliana Haig
4,239 Points

Thank you! I really appreciate it. I was wondering if I really needed that loop but I think I defaulted to it because it was one of the latest things I've learned.

Here is a different approach to the loop:

var students = [

{   name: 'Luke',
    track: 'iOS',
    achievements: 5,
    points: 2408
},

{   name: 'Juan',
    track: 'Java',
    achievements: 7,
    points: 5455
},

{   name: 'Emily',
    track: 'Front End',
    achievements: 10,
    points: 6799
},

{   name: 'Jason',
    track: 'Full Stack',
    achievements: 8,
    points: 5432
},

{   name: 'Anne',
    track: 'Ruby',
    achievements: 11,
    points: 8905
},

];

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

 var message = "";  

// creates a counter to cycle through the list
    for ( prop in students ) {

   message += `

     <div>
     <h2>Student Info:</h2>
     Name: ${students[prop].name} <br>
     Track: ${students[prop].track} <br>
     Achivements: ${students[prop].achievements} <br>
     Points: ${students[prop].points}
     </div>

   `;
 }

print(message);

Cheers.

Pieter Bracke
Pieter Bracke
4,078 Points

that'll also do the trick :)

Eliana Haig
Eliana Haig
4,239 Points

Thanks so much! As far as I can tell from my notes, I haven't encountered the notation of the $ in front of {} like you show. What is that called? I can't find it on MDN but then I don't know what to search for :-) Thanks!

It's called "template literal", it's a newer tech, so it's still not supported on all the browsers, only good browsers support it, meaning IE won't supported.