Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Tracking Multiple Items with Arrays Useful Array Methods

Can you use while(search !== 'quit'){} to write this task?

Can you use while(search !== 'quit'){} to write this task?

1 Answer

Steven Parker
Steven Parker
217,443 Points

I assume you mean 'quit' instead of 'quite'; but while it wouldn't hurt it's not needed, since the code already makes the same test (with the opposite comparison) and exits the loop immediately using "break". And to conform to "best practice", you'd also need to pre-assign something (other than 'quit') to the variable before the loop.

Thanks a lot for your reply. I do not quite get you. I wonder instead of writing the code this way:

while(true){
search = prompt('Search for a product in the store.');
if ( search === 'quit'){
break;
}
}

can we write the code this way:

do{
search = prompt('Search for a product in the store.')
}while(search !== 'quit');
Steven Parker
Steven Parker
217,443 Points

For these small snippets, yes those are equivalent and the second one is more efficient.

But in the video, there is some other code inside the loop that would make these not equivalent.