Lessons 3 & 4: Cannot read property 'toUpperCase' or 'toLowerCase' of null


#1

When I initiatially did exercise 3, this was my code:

var user = prompt("Where do you want to go on vacation?").toLowerCase();

The console said I did it right, then I moved on to exercise four. Here's my code:
var user = prompt("Where do you want to go on vacation?").toLowerCase();

switch(user) {
case 'Costa Rica':
console.log("OMG, I want to LIVE there!!!");
break;

case 'Thailand':
    console.log("That could be cool.");
    break;

case 'Kentucky':
    console.log("Who the ■■■■ wants to go to friggin KENTUCKY?!");
    break;

default:
console.log("Ooh, I want to go there too! Let's book a trip!");

}

I got an error message saying, "TypeError: Cannot read property 'toLowerCase' of null". What does that even mean? I went back to part three and I got that message as well. Mind you, this is AFTER it said my answer was correct. Any suggestions>


#2

The JS prompt() function returns two psssible values:

  1. A string value (may be the empty string)
  2. null

The second return value is the result of clicking Cancel or pressing the Esc key. When this value has any string method invoked on it, JavaScript will throw an exception, a TypeError. You have now seen the error message that results. This will stop a program dead in its tracks.

The cure is to NOT chain a string method of any kind to prompt(). Test the return value for stringiness first, then if it is a legimate string, run all the string methods on it you wish.


#3