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

Zijun Liao
Zijun Liao
13,409 Points

Cancel button not working for while loop

I tried to run loop for getting input, However, the cancel button is not working, I print out the input, it appears null though, anyone knows the reason?

do{

    var name = prompt('Please type the student name');

    console.log('#'+name+"#");

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

        if(students[i].name===name){

            console.log(name + ":" + students[i].Achievements + ' : ' + students[i].track);
        }
    }
} while(name!=='exit' && name!=='' && name!=null);   //First 2 condition work, not last
Antonio De Rose
Antonio De Rose
20,885 Points

is this a challenge, can you locate to the challenge.

1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi Zijun Liao,

Typically you would only want a single condition to define when the loop should end. Below is an example of how to accomplish this by moving the 3 conditions to within the loop and breaking the cycle using a single condition.

let shouldRun = true;

do {
  const name = prompt('Please type the student name');

  if (name === 'exit' || name === '' || name === null) {
    shouldRun = false;
  } else {
    // Normal loop execution here...
  }
} while (shouldRun === true);

As can be seen, our core logic is now encapsulated inside the loop while we check for the condition and break the cycle with shouldRun once a specific condition has been met.

Hope that helps.