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 trialThomas Katalenas
11,033 PointsBug
I found a bug, you type things that aren't on the list and prompt will return Yes, we have butter in the store.
butter is not in the list though....hmm
in python we'd do something like this.
for word in list: if word not in list: return False
var inStock = [ 'apples', 'eggs', 'milk', 'cookies', 'cheese', 'bread', 'lettuce', 'carrot', 'broccoli', 'pizza', 'potato', 'crackers', 'onion', 'tofu', 'frozen dinner', 'cucumber'];
var search;
var index;
var item;
function print(message) {
document.write( '<p>' + message + '</p>');
}
while (true) {
search = prompt("Search for a product in our store. Type 'list' to show all the produce and 'quit' to exit");
if (search === 'quit'){
break;
}else if (search === 'list') {
print(inStock.join(', '));
}else {
if ( inStock.indexOf(search)) {
print( 'Yes, we have ' + search + ' in the store.');
} else {
print( search + ' is not in stock.');
}
}
}
3 Answers
Thomas Katalenas
11,033 Pointswhat is the difference between
if ( inStock.indexOf(search) != -1) and if ( inStock.indexOf(search) !== -1)
Daniel Perez Alvarez
4,233 PointsIt seems that you forgot to check the return value of indexOf(search)
. That's why, no matter what item you enter, it would be always available in your store. Try adding this instead:
if ( inStock.indexOf(search) > -1 ) {
print("Yes, we have " + search + " in our store.");
}
Daniel Perez Alvarez
4,233 PointsIt seems that you forgot to check the return value of indexOf(search)
. That's why, no matter what item you enter, it would be always available in your store. Try adding this instead:
if ( inStock.indexOf(search) > -1 ) {
print("Yes, we have " + search + " in our store.");
}
michael mead
7,205 Pointsmichael mead
7,205 Points!== is "strict equality operator". It compares value and type. Non-strict equality operators only compare value and would return true for "9" and 9 even though "9" is a string.