0

I'm very new to JavaScript and I'm trying to learn some basics practicing with it.

I've got stuck with this:

var name = prompt('enter your name', '');

if( name == null ) {
    alert('Cancelled');
} else if ( name == 'admin' ) {
    alert('hi admin');
} else {
    alert('I don\'t know you');
}

If I press esc (or cancel button) I should get 'Cancelled' message, but it's 'I don\'t know you' by some reason.

But the fun part is if I'll rename variable to something else, for ex.:

var usr = prompt('enter your name', '');

if( usr == null ) {
    alert('Cancelled');
} else if ( usr == 'admin' ) {
    alert('hi admin');
} else {
    alert('I don\'t know you');
}

...It will work just fine.

What's wrong? I've tried it in different browsers, I've googled forbidden variable names, but I have no answer.

PS: I know that esc or cancel will return empty string in safari, but it happens in all browsers

lencdv
  • 3
  • 2
  • Both snippets work just as expected for me, I get "Cancelled" when I press esc. – CertainPerformance Mar 21 '18 at 23:12
  • I suggest that you include an option to check if the dialog box was closed. Here, Add this to your if function `else if(window.close){alert("Cancelled")}` – Abiud Orina Mar 21 '18 at 23:21
  • The code is working per specification. If the user presses escape without entering text, the prompt returns an empty string. [See W3 Documentation:][1] > Return Value: A String. If the user clicks "OK", the input value is > returned. If the user clicks "cancel", null is returned. If the user > clicks OK without entering any text, an empty string is returned. Also, you should use triple equals operator for equality. if (user === null) ... else if (user === 'admin')... To answer your question about the variable `name`, yes, this is a duplicate issue – Joshua Manns Mar 21 '18 at 23:22
  • It seems I'm so bad in searching. Thanks to Barmar, who do it better than me. Variable 'name' can cause conflicts, so it's better to give it another name when using as a global variable. – lencdv Mar 21 '18 at 23:26

2 Answers2

0

Possibly you declare some element via id=name. The element will be assigned to name.

Just set a breakpoint in the debugger and look at the values. Scope your code and use let/const and never var.

(() => {
    let name = prompt('enter your name', '');
    // ...
})();
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • I just tried it and I see that name variable returned 'null' as a string, so I can fix it with name == 'null' But the second example still works fine with usr == null – lencdv Mar 21 '18 at 23:17
  • Something, somewhere is setting the name variable. Which is why everything should be scoped and you should use `let`/`const` and never `var`. – H.B. Mar 21 '18 at 23:18
0

The esc key is NOT an input key, it's only used to interrupt a program's current status ...so I advise you use

if(!name)// instead of 
if(name == null)