Problem with .toLowerCase () at prompt

0

I have this basic code and it works well when I write the name.

 var user = prompt("Cual es tu nombre").toLowerCase();
    
    if (user) {
        console.log("Hola " + user);
    } else if (user === null) {
        console.log("Adios " + user);
    }

The problem comes when I give it to cancel. I miss this error in the console:

  

Uncaught TypeError: Can not read property 'toLowerCase' of null

Is there any way I can print the content if cancel is given?

    
asked by jaumeserr 25.05.2018 в 18:50
source

2 answers

3

This no longer generates an error

 var user = prompt("Cual es tu nombre","");
    if(user != null)
user= user.toLowerCase();

    if (user) {
        console.log("Hola " + user);
    } else if (user === null) {
        console.log("Adios " + user);
    }
    
answered by 25.05.2018 / 19:00
source
1

Hello, the problem is that when you give cancel the follow the .toLowerCase() a solution that I propose is to validate if the name variable has something defined and only execute the method if it has something assigned.

var name = prompt("Cual es tu nombre")
    var user = name ? name.toLowerCase()  : null ;
        
    if (user) {
        console.log("Hola " + user);
    } else if (user === null) {
        console.log("Adios " + user);
    }
    
answered by 25.05.2018 в 19:00