Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
215,269 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);