0

I cant seems to get this to work.

<script language="JavaScript">
var name = null;
do
{
    var name = prompt("Please enter your full name","");
}
while(name != null);
</script>
1
  • "" != null is true. You want while (name == null) (although I'd recommend name == "") Commented Jun 17, 2015 at 3:51

2 Answers 2

1

When you enter a blank string and press OK, it returns a empty string not null, null is returned only when you press cancel.

You can test for truthyness of the returned value

var name = null;
do {
  name = prompt("Please enter your full name");
  console.log(name)
}
while (!name);
console.log('done', name)
Sign up to request clarification or add additional context in comments.

Comments

0

I would use a boolean value:

var name = false;
do
{
    name = prompt("Please enter your full name",'');
}
while(!name); // While name is not true

Also you were re-declaring the name var again on within the do loop, remove the var in the loop.

4 Comments

Why introduce another type? Also, the redeclaration is not really a problem.
Thanks similarly how do i validate the input is a date? i cant seem to get .typeof to work
@Bergi Good point. I used a type to make the logic easier to understand, but does this have a performance cost? Might be worth it. As for calling var again, agreed this isn't a problem but it's still not necessary nor good practice IMO. Cheers
Using false makes everything even more confusing. Now name is undefined before being initialised, then false, then either null or a string (depending on what prompt returned). I'm not talking about performance costs, but about best practises indeed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.