Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
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 Respuestas
Responde la pregunta

0

Please, you should use if (!username).

Because prompt can return undefined/null instead empty string.

about 4 years ago · Santiago Gelvez Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda