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 Arrays Loop Through Arrays Locate and Join Array Elements

Davi Laurindo Grah
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Davi Laurindo Grah
Front End Web Development Techdegree Graduate 17,337 Points

Why after change de prompt search all toLowerCase() the index position of the strings in the array looses the +1?

In this code, when i search in the prompt all in lower case the index position counts the +1. But when I type any caps letter it just ignore the +1 of the index position.

If I search pizza it shows #1 if I search Pizza it shows #0

const inStock = ['pizza', 'cookies', 'eggs', 'apples', 'milk', 'cheese', 'bread', 'lettuce', 'carrots', 'broccoli', 'potatoes', 'crackers', 'onions', 'tofu', 'limes', 'cucumbers']; const search = prompt('Search for a product.'); let message;

if ( !search ) { message = <strong>In Stock:</strong> ${inStock.join(', ')}; } else if ( inStock.includes(search.toLowerCase()) ) { message = Yes, we have <strong>${search}</strong>. It's #${inStock.indexOf(search)+1} on the list!; } else { message = Sorry, we do not have <strong>${search.toLowerCase()}</strong>. }

document.querySelector('main').innerHTML = <p>${message}</p>

2 Answers

else if ( inStock.includes(search.toLowerCase()) ) { 
    message = `Yes, we have <strong>${search}</strong>. It's #${inStock.indexOf(search)+1} on the list!`; 
}

In the if statement, the code checks if the lower case version of the search string is in inStock, but it does not modify the search string. If the if statement is true, it determines the index of the search string without making it lower case first. If search is not in inStock, even if search.toLowerCase() is in inStock, then inStock.indexOf(search) will be -1, meaning that the item was not found. The code then adds 1 to the result, giving you 0.

Try changing the declaration of search to const search = prompt('Search for a product.').toLowerCase(); or checking the lower case version of search in message.

message = `Yes, we have <strong>${search}</strong>. It's #${inStock.indexOf(search.toLowerCase())+1} on the list!`; 

You have a syntax error switch inStock.includes(search.toLowerCase()) ) with inStock.includes(search.toLowerCase()). I think that the index of method is returning -1 because of the syntax error -1 + 1 = 0.