Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
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 Respostas
Responde à pergunta

0

Please, you should use if (!username).

Because prompt can return undefined/null instead empty string.

about 4 years ago · Santiago Gelvez Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda