This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by ZMO
almost 9 years

TypeError: Cannot read property 'toLowerCase' of null

any help will be great TypeError: Cannot read property ‘toLowerCase’ of null what will be the solution for such a problem; the code is :::::: var user = prompt(“ZANA”).toLowerCase();

Answer 55f4b0519113cbccab00037e

0 votes

Permalink

@ZMO,

This is a topic I have written about many times in these forums, mostly as a rant, mind you, so not likely good reading. The solution is to not chain the string method directly to the prompt() function.

Yes it works fine most of the time and even makes sense, provided the output is always a string, empty or with some length. Consider the return values of prompt():

""        => empty string with length 0
"string"  => string with length > 0
null      => null value (not a string)

Clicking OK or pressing Enter will return a string, empty or otherwise. Clicking Cancel or pressing Esc will return null. This will throw the ReferenceError you are seeing when we try to apply a string method to the return value.

null has no properties, and is not even an object. It has no prototype. We cannot apply any methods to it.

The long term solution is to create a function that we can pass in a prompt string and expected input requirements and have the function prompt the user, and continue to prompt the user until it gets acceptable inputs or Cancel/Esc. Or we can use an inline approach if it is not repeated…

user = prompt(' ? ');
if (user && user.length) {
    // test the input
    // run with the input
} else {
    // quit the program
}

In the above,

user will be `null` or something, as in F or T
user.length will be 0 or a positive number, as in F or T

Only T && T will pass. Note that we have to test for null first, since it has no length property and will throw an error if the other expression is tested first.

I could go into much more detail with code examples but would rather not complicate matters any more than they already are. Browse the Q&A for threads on this topic and you should be able to come across several examples.

points
Submitted by Roy
almost 9 years