This forum is now read-only. Please use our new forums! Go to forums
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
@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.
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency