bonum77 bonum77 - 2 months ago 6
Javascript Question

Can someone explain to me why i can't make this simple code work. thank you

I just started learning javascript and after learning loops and if else i wanted to write a small program that's asked the user it's name and it is empty or its a number it will keep asking the user until it's a valid name. First if i write a string it will write to html but when program trying to run the loop it will fail to write the valid name.



var getName = prompt("What is your name ? ");


if (getName === null || !isNaN(getName)){

while (getName !== null || isNaN(getName)){
alert("Invalid name, please try again");
getName = prompt("What is your name ? ");
if (getName !== null || isNaN(getName)){
document.write("Hello ", getName);
}
}
}else {
document.write("Hello ", getName);
}





Can someone explain it to me why my code does not work after getting into loop and after entering a valid thing program still says "it's not a valid name try again"

When did I messed up. I am really bad at programming lol

Answer

You could use the condition getName === null || !isNaN(getName) instead, check the following example.

Hope this helps.

var getName = null;

while (getName === null || !isNaN(getName)){
  getName = prompt("What is your name ? ");

  if (getName === null || !isNaN(getName)){
    alert("Invalid name, please try again");
  }else{
    document.write("Hello ", getName);
  }
}