Back to the lesson

Check the login

importance: 3

Write the code which asks for a login with prompt.

If the visitor enters "Admin", then prompt for a password, if the input is an empty line or Esc – show “Canceled.”, if it’s another string – then show “I don’t know you”.

The password is checked as follows:

  • If it equals “TheMaster”, then show “Welcome!”,
  • Another string – show “Wrong password”,
  • For an empty string or cancelled input, show “Canceled.”

The schema:

Please use nested if blocks. Mind the overall readability of the code.

Run the demo

let userName = prompt("Who's there?", '');

if (userName == 'Admin') {

  let pass = prompt('Password?', '');

  if (pass == 'TheMaster') {
    alert( 'Welcome!' );
  } else if (pass == null || pass == '') { // (*)
    alert( 'Canceled.' );
  } else {
    alert( 'Wrong password' );

} else if (userName == null || userName == '') { // (**)

  alert( 'Canceled' );

} else {

  alert( "I don't know you" );


Please note the if check in lines (*) and (**). Every browser except Safari returns null when the input is canceled, and Safari returns an empty string. So we must treat them same for compatibility.

Also note the vertical indents inside the if blocks. They are technically not required, but make the code more readable.