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

I managed to get everything working but I'm not sure why!?

Hi all,

I have really struggled with this challenge but finally got it to work. Although it is working, I'm a little unsure why?

I understand everything but the condition in my do while loop. I wanted the condition to be "If flag = True or variable search does not = 'quit' loop again. However this does not work as I expected but does work when I use and &&.

Can someone please explain why as I don't understand. Also, when running my code I get an error "Uncaught TypeError: Cannot read property 'toLowerCase' of null on line 17 at student report.js.17" and I can't fix.

Thank you!

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

let search;
let name;
let html = '';
let flag = true;

do {
  search = prompt('Search Student Record: Type Name or Type "Quit" to End'); 

  for (let i = 0; i < students.length; i++) {
    name = students[i].name;

    if (name.toLowerCase() === search.toLowerCase()) {
      flag = false;
      html += `<h2>Student: ${students[i].name}</h2>`;
      html += `<p>Track: ${students[i].track}</p>`;
      html += `<p>Achievements: ${students[i].achievements}</p>`;
      html += `<p>Points: ${students[i].points}</p>`;
      print(html);
    }
  }
} while (flag && search.toLowerCase() !== 'quit');

1 Answer

Steven Parker
Steven Parker
231,268 Points

When you test for the opposite of certain conditions, you also combine the tests with the opposite logic.

The condition says the loop should continue running as long as "flag" remains true, and the search term is not "quit". So that means the loop ends if "flag" becomes false (when something matched) OR someone types "quit".

And I'd guess the TypeError only occurs when you cancel the prompt instead of entering "quit", right? That's because the cancel causes "prompt" to return null instead of a string (even an empty one) that you could call "toLower" on. You'll need to handle that case explicitly to make the handling of "cancel" more graceful.