javascript - Is there any easier or shorter way to write this repeat code? -
i wondering if there shorter/ easier way write repeating code. if name entered prompt box doesn't have send error message , reput it.
just dont have explain alot, heres code:
function error() { alert('you must enter name.'); } var name = prompt('what name?', 'name'); function repeat() { var name = prompt('what name?', 'name'); if(name === '') { error(); repeat(); } } if(name === '') { error(); repeat(); }
like this:
var name; while(!(name=prompt('what name?', 'name'))) { alert('you must enter name.'); }
how works
the while
loop repeats until condition met. in case, condition is:
!(name=prompt('what name?', 'name'))
this part of expression assigns prompt
value name
(as you're aware):
name=prompt('what name?', 'name')
in javascript, assignment variable returns value. (that's why can chain assignments such a = b = c = 16
.)
so if enter "johnathan" name, expression becomes "johnathan":
(name=prompt('what name?', 'name'))
if enter nothing name, expression becomes null string.
the logical not operator (!
) before expression returns boolean opposite of "truthiness" of expression. string value truthy, null string falsy.
by applying not operator expression:
!(name=prompt('what name?', 'name'))
… loop continue until name
variable has value.
final thought: convention, variables should begin lowercase letter. haven't done here, because name
property of window
, , changing window's name lead problems. ideally, prompt within function, wouldn't have global variables. if case, use variable name
others have suggested.
Comments
Post a Comment