Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
Javascript prompt issue

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;
  }
}
about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

Please, you should use if (!username).

Because prompt can return undefined/null instead empty string.

about 4 years ago · Santiago Gelvez Report

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 */ }

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!