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 trialAlejandro Galiano
6,613 PointsI did it with a "do/while loop" and it works. Can you check if this is correct in terms of best practices?
Hi all! I tried to write the program before watching the whole video and its final solution. I just wanted to share with you the code and to check if someone more expert could tell me if it is as valid as the final solution in terms of DRY, understanding the program, syntax, etc.
var inStock = [ 'apples', 'eggs', 'milk', 'cookies', 'cheese', 'bread', 'lettuce', 'carrot', 'broccoli', 'pizza', 'potato', 'crackers', 'onion', 'tofu', 'frozen dinner', 'cucumber'];
var search;
function print(message) {
document.write( '<p>' + message + '</p>');
}
do {
search = prompt("Hi! Search for a single product in our store").toLowerCase();
if(search === "list"){
print(inStock.join(", "));
} else if (search === inStock[inStock.indexOf(search)]){
print("Yes, we have " + search + " in our store.");
} else if (search !== "quit") {
print(search + " is not in stock.");
}
} while (search !== "quit")
Many thanks in advance.
AG
1 Answer
Shreyash Agarwal
9,843 PointsThis is actually better practice, speaking from my programming experience.
Do while ensures that the loop runs atleast one according to syntax. The same can be done using a while() loop, however that requires the existing variable inside the evaluation to evaulate to true, before it runs the loop.
As far as user based interactions are concerned when you really WANT something to happen for sure at least once, use a do while. In short, kudos! You were spot on to do that!
Alejandro Galiano
6,613 PointsAlejandro Galiano
6,613 PointsThanks for your answer Shreyash!