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!

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

Are there other ways that I could've made this code much shorter/Is this following best coding practices?

var students = [
  {name: "Asia", track: "Front End Development", achievements: 3100, points: 4000},
  {name: "Bien", track: "iOS", achievements: 100, points: 200},
  {name: "Bea", track: "PHP", achievements: 2100, points: 3000},
  {name: "Bella", track: "Business Development", achievements: 1100, points: 3000},
  {name: "Basil", track: "Web Design", achievements: 200, points: 200},
  {name: "Faye", track: "Ruby", achievements: 4100, points: 5000}
];

var name = "",
    track = "",
    achievements = "",
    points = "",
    studentList = "";


function print(message) {
  var outputDiv = document.getElementById("output");
  outputDiv.innerHTML = message;
  };


for (var i=0; i<students.length; i++) {
    name = students[i].name;
    track = students[i].track;
    achievements = students[i].achievements;
    points = students[i].points;
    studentList += "<h2>Student: " + name + "</h2>" + "<p> Track: " + track + "</p>"+ " Achievements: " + achievements + "</p>" + " Points: " + points + "</p></br>";
    print(studentList);
}

The code works. Just want to know if there are other ways that could better my code?

1 Answer

Steven Parker
Steven Parker
228,001 Points

It could be a bit more compact.

I'm not sure this is significantly "better" from the standpoint of "best practices", but it can be a bit smaller if you eliminate some variables and use string interpolation.

// var students = ... (no change to students array)

function print(message) {
  document.getElementById("output").innerHTML = message;
}

var studentList = "";
for (let student of students) {
  studentList += `<h2>Student: ${student.name}</h2>
                  <p>Track: ${student.track}</p>
                  <p>Achievements: ${student.achievements}</p>
                  <p>Points: ${student.points}</p></br>`;
}
print(studentList);