Like this:
var Name;
while(!(Name=prompt('What is your name?', 'Name'))) {
alert('You must enter a name.');
}
How it works
The while
loop repeats until a condition is met. In this case, the condition is:
!(Name=prompt('What is your name?', 'Name'))
This part of the expression assigns the prompt
value to Name
(as you're already aware):
Name=prompt('What is your name?', 'Name')
In JavaScript, an assignment to a variable also returns the value. (That's why we can chain assignments such as a = b = c = 16
.)
So if you enter "Johnathan" as the name, this expression becomes "Johnathan":
(Name=prompt('What is your name?', 'Name'))
If you enter nothing as the name, the expression becomes a null string.
The logical NOT operator (!
) before an expression returns the boolean opposite of the "truthiness" of the expression. A string value is truthy, but a null string is falsy.
By applying the NOT operator to the expression:
!(Name=prompt('What is your name?', 'Name'))
… the loop will continue until the Name
variable has a value.
Final thought: By convention, variables should begin with a lowercase letter. I haven't done that here, because name
is a property of window
, and changing the window's name could lead to problems. Ideally, your prompt would be within a function, so that you wouldn't have any global variables. If that were the case, you could use the variable name
as others have suggested.