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

Julianna Kahn
Julianna Kahn
20,700 Points

Please help explain this code to me...

https://w.trhou.se/bwva9e5caa I was working on this challenge and the student_v1 is the version I got to work on my own. Admittedly it is not the most elegant solution. But I don't understand why the solution print function given in the the challenge solution doesn't work in my file: var outputDiv = document.getElementById('output'); outputDiv.innerHTML = message; but the print function using document.write() does. (You will see the function commented out because I was testing each version.)

Also, in my solution, I used the code:
name = students[i].name; Why does that work when the code used in the solution is: name = students[i];

2 Answers

Antony .
Antony .
2,801 Points

Hi, Julianna Kahn

Let's take a look at this section of your code.

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

print('<h1> ' + 'Student:  ' +  name + ' </h1>');
print('<p> ' + 'Track:   ' + track + ' </p>');
print('<p> ' + 'Badges:  ' + badges + ' </p>');
print('<p> ' + 'Points:  ' + points + ' </p>');

When calling your print function you are technically replacing your content every time you call it. So an example would be the document.write() method.

document.write("<h1> Hi I'm a level 1 heading </h1>")
document.write("<h2> Hi I'm a level 2 heading </h2>")
document.write("<h3> Hi I'm a level 3 heading </h3>")
document.write("<h4> Hi I'm a level 4 heading </h4>")

Which one will print out? Well all of them will. Why? because you are replacing the contents of your body page every time you call it. This is the same as you calling your print function.

So if you want a quick fix you can simply change this line of code inside your print function:

outputDiv.innerHTML = message;

to this:

outputDiv.innerHTML += message;

Because now you won't be replacing content when your function is called more than once.

Julianna Kahn
Julianna Kahn
20,700 Points

Thanks for your explanation. Also, can you tell me how to put my snapshot into a new file? I wanted to test it out to better understand, apparently my original file was overwritten. When I try to copy/paste the snapshot into a new workspace, it is filled with line numbers.