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! While you're at it, check out some resources Treehouse students have shared here.
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 trialDIJITUL UK
17,246 PointsWorking code: But how can It be improved?
function print(message) {
document.getElementById('output');
output.innerHTML = message;
}
var html = "";
var students = [
{name: "Liam", track: "Javascript", achievements: 10002, points: 11188},
{name: "Ben", track: "PHP", achievements: 50, points: 11188},
{name: "Charlotte", track: "CSS", achievements: 50, points: 11188},
{name: "Dave", track: "Wizardry", achievements: 50, points: 9001},
{name: "Jake", track: "Wordpress", achievements: 50, points: 11188}
];
for (var i = 0; i < students.length; i++) {
html += "<h2>Student: " + students[i].name + "</h2>";
html += "<h3>Track: " + students[i].track + "</h3>";
html += "<h3>Achievements: " + students[i].achievements + "</h3>";
html += "<h3>Points: " + students[i].points + "</h3>";
print(html);
}
Just wondering how this can be improved, shortened, made modular and reusable etc.
1 Answer
Lucas Santos
19,315 PointsWell you can shorten your print method:
function print(message) {
document.getElementById('output').innerHTML = message;
}
and I would not call the print method within the loop like you have it. I would call it outside the loop like this:
for (var i = 0; i < students.length; i++) {
html += "<h2>Student: " + students[i].name + "</h2>";
html += "<h3>Track: " + students[i].track + "</h3>";
html += "<h3>Achievements: " + students[i].achievements + "</h3>";
html += "<h3>Points: " + students[i].points + "</h3>";
}
print(html);
Because your html variable is global so with each iteration of the loop you're already appending the values of students to the html variable at the top. Meaning you only need to call your function once and not 5 times like it's doing.