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 trial

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Student Record Search Challenge Solution

Pooria Rashidi
Pooria Rashidi
9,740 Points

Newly printed student info not replacing previously printed student info

Originally I had the loop looking like this (I left out the variables and print function):

while ( true ){
  var input = prompt('Name or Quit');
  if (input === null || input.toLowerCase() == 'quit') {
      break;
  } else {
      for (var i = 0; i < students.length; i += 1) {
          student = students[i];
          if (input.toLowerCase() == student.name.toLowerCase()) {
          message += '<h2>Student: ' + student.name + '</h2>';
          message += '<p>Track: ' + student.track + '</p>';
          message += '<p>Points: ' + student.points + '</p>';
          message += '<p>Achievements: ' + student.achievements + '</p>';
          print(message);
          }

When I put in a student name it would just print the new one after the existing ones on the page. After moving the message+= lines out of the loop and into a function (like in the video) the program overwrites the existing info with the newly printed info (as the challenge demanded).

Why did this change happen?

Thanks so much!

2 Answers

Vijay Strickland
Vijay Strickland
1,734 Points

When a variable is created inside a function it will be recreated each time the function is run, so each time a result is sent to that function it will overwrite the previous value.

Sorren Prime
PLUS
Sorren Prime
Courses Plus Student 2,022 Points

Are you using the document.write function for your print function or the .getElementById method?

Pooria Rashidi
Pooria Rashidi
9,740 Points

Yeah I was using the getElementById one, it's just the print function that was in the workspace already.