Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.