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') {
  } 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.