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

Wojciech Kwiatkowski
Wojciech Kwiatkowski
5,856 Points

toLowerCase() method makes problem

Everything with my script is ok until I add the toLowerCase() method. Why is it a problem? Am I writing it wrong? When I add toLowerCase() in line 4, the script does not open and DevTools shows me that comment: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined.

What is wrong?

Below is my script. Please help.

var inStock = [ 'apples', 'eggs', 'milk', 'cookies', 'cheese', 'bread', 'lettuce', 'carrot', 'broccoli', 'pizza', 'potato', 'crackers', 'onion', 'tofu', 'frozen dinner', 'cucumber'];
var search;
search = search.toLowerCase();
function print(message) {
  document.write( '<p>' + message + '</p>');
}

while (true) {
  search = prompt ("Search for a product in our store. Type 'list' to show all of the produce and 'quit' to exit");
  if (search === 'quit') {
    break;
  } else if (search === 'list') {
    print (inStock.join (', ') )
  } else {
    if (inStock.indexOf (search) > -1) {
      print ("Yes, we have " +search +" in the store.");
    } else {
      print ("No, we do not have " +search +" in the store.");
    }
  }
}

2 Answers

Where you have it now search has been declared, but nothing has been assigned to the variable yet which is causing the error.

search = search.toLowerCase() should be moved into the loop just after the prompt so that you update the current value of search.