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

239
Visualizações
Else statement not working when comparing numbers

I have been messing with this for awhile now and i cant seem to figure out why the else statement does not show up when i type any negative number into the prompt box, i have tried to create an additional if statement using Math.sign(num) to check if the number is negative to check if its less than zero but i havent had any luck making it work. my thought was to rule out other possibilities and if all the above statements were false the number had to be negative. What am i doing wrong here?

var num = parseFloat(prompt("please enter a number", ""));

var barRepeat = "*".repeat(num); //made this to get a visual bar displaying * equal to the number given

if (num > 0) {
  document.write(num);
  document.write("=>");
  document.write(barRepeat);
} else if (num == 0) {
  document.write("The number you entered is 0");
} else if (isNaN(num)) {
  document.write("error you entered an invalid character");
} else {
  document.write("the number you entered is negative, please try again");
}

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you enter a negative number, "*".repeat(num) gets an error and the script stops there, without ever going to the if statements.

Move that into the if statement so you only create the repeat bar when the input is valid.

var num = parseFloat(prompt("please enter a number", ""));

if (num > 0) {
  var barRepeat = "*".repeat(num); //made this to get a visual bar displaying * equal to the number given
  document.write(num);
  document.write("=>");
  document.write(barRepeat);
} else if (num == 0) {
  document.write("The number you entered is 0");
} else if (isNaN(num)) {
  document.write("error you entered an invalid character");
} else {
  document.write("the number you entered is negative, please try again");
}

Whenever a JavaScript function doesn't behave as you expect, the first place you should look is the console for error messages.

Also, see Why is document.write considered a "bad practice"?

about 4 years ago · Juan Pablo Isaza 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