Consider this code:
var name = prompt("What is your name", "Anonymous");
if (name == null) {
alert("detected null");
name = "Anonymous";
}
alert("Hello " + name);
It is my understanding that clicking [Cancel] or pressing the [Escape] key will cause the JavaScript window.prompt(text, [default])
function to return null
(or perhaps undefined
in older versions of IE)
When I execute the above code in Firefox, the expected prompt appears. However, when I press [Escape], I never see the "detected null" message (and the name variable is not set to "Anonymous". It is as if the name
variable is not being set to null
. Interestingly, the last alert displays "Hello null".
I've tried swapping out the name == null
check with name === null
with the same behavior.
How does one detect null
in JavaScript?
Please note: I am really trying to detect null, not an empty string.