0

So i'm doing a user input with prompt and i've done an if statement where if the prompt vas empty it would return alertbox with a warning. The problem is when i press ok on the alert. It puts me right in to the app. here is my code.

function getName(){
  var username = prompt("Write your username");
  if(username == ""){
    alert("Please write your username");
  }
  else{
    return username;
  }
}
  • you need to do a loop. however, `alert` and `prompt` are discouraged – Daniel A. White Apr 12 '22 at 15:45
  • What do you mean by "puts me right in to the app"? What specifically isn't working as expected in the code shown? Please clarify the specifics of the problem you are observing. – David Apr 12 '22 at 15:46
  • You should check it for null as well - [the doc](https://www.w3schools.com/jsref/met_win_prompt.asp) - _If the user clicks "OK", the input value is returned. Otherwise null is returned_ – folibis Apr 12 '22 at 15:49

2 Answers2

0

Please, you should use if (!username).

Because prompt can return undefined/null instead empty string.

denelvis
  • 21
  • 1
  • 2
0

When I click "OK" at the prompt without entering any text, I do get an alert with "Please write your username", so that code does appear to be working.

It's worth noting that you are checking for an empty string, but you should also be checking for null.

When the user clicks the OK button, text entered in the input field is returned. If the user clicks OK without entering any text, an empty string is returned. If the user clicks the Cancel button, this function returns null.

https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt#return_value

You may also want to be aware the fact that some older versions of IE do return undefined, although I don't know anyone currently supporting IE.

Note that in Internet Explorer 7 and 8, if you do not provide this [default] parameter, the string "undefined" is the default value. https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt#parameters

You can check for truthiness in one expression with:

if(!username){
   // do stuff...
}

This will check for empty string, undefined, null, 0, false, and NaN.

See this post: What does this mean: if( variable ){ /* do something */ }

Josh
  • 3,872
  • 1
  • 12
  • 13