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 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
231,268 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
231,268 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.