Name == null is broken

<script>
    var name = prompt("whats your name")
    alert(name)
    if(name === null) {
        alert("don't press cancel")
    }
</script>

It should say ‘don’t press cancel’ but no alert pops up

It works for me.

Keep in mind that this behavior only operates when the user clicks Cancel - clicking OK with an empty text box is NOT the same thing (Null vs Empty String)

2 Likes

UPDATE: It works on internet explorer but not chrome, edge, firefox or opera

Here are my test results, for when using http://jsfiddle.net/7Lj2t5cu/1/ to test the “don’t press cancel” message.

                  Press Esc    Cancel button    Enter button
IE                     [ JSFiddle   doesn't   load ]
Chrome               ✅             ✅              ❌
Edge                 ✅             ✅              ❌
Firefox              ✅             ✅              ❌
Opera                ✅             ✅              ❌

Are you using http://jsfiddle.net/7Lj2t5cu/1/ to test these things, or something else?

When testing with a local HTML file, Internet Explorer shows undefined in the prompt, so we need to also pass a default text value with the prompt.’

When testing elsewhere, the string of “null” is returned from prompt instead of the null object, so the following code tests as being more reliable.

    var name = prompt("whats your name", "");
    if(name === null || name === "null") {
        alert("don't press cancel");
    }

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.