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

Doug Sammond
Doug Sammond
1,318 Points

document.write() in a while loop?

I think I'm missing something pretty basic. I expect the following code to prompt for a Search Name. If the string is not "Quit", I would expect it to write "No match found" and return to the prompt. However, after entering names other than "Quit", I see "No match foundNo match found" (indicating twice through the loop) and no further prompt. I'll appreciate any help. Thanks!

var queryName = '';

while (true) { queryName = prompt('Search for Name'); if (queryName.toLowerCase() === null || 'quit') { break; } document.write('No match found'); }

2 Answers

Steven Parker
Steven Parker
171,120 Points

Combining two terms with a logical operator (like "||") creates a single boolean result from them, which is likely not what you intended. To test both values, you need complete comparison expressions on both sides of the logical operator:

 if (queryName === null || queryName.toLowerCase() ===  'quit')
Doug Sammond
Doug Sammond
1,318 Points

Thanks for the response! That works a little better, but I'm still getting a response I don't understand. Now with the following change, the code returns to the prompt, but when "Quit" is entered, it breaks from the loop and writes "No match foundNo match found". Shouldn't it skip the rest of what's in the loop after the "break;" command and not render the document.write('No match found') step? And, why is it duplicating it? Thanks for any further help!

var queryName = '';

while (true) { queryName = prompt('Search for Name'); if (queryName.toLowerCase() === 'quit') { break; } document.write('No match found'); }

Steven Parker
Steven Parker
171,120 Points

You should see "No match found." repeated for each word you enter before "quit". If "quit" is the very first thing you input, the page should be blank.