While trying to learn JavaScript I came across a few snippets of code that has confused me.
My original code that I was messing around with was:
var username = prompt("Choose a username:");
if (username === null) {
alert("Username is required!");
} else {
console.log("Your username is: " + username);
}
This didn't work. So I came here and found this question: How to determine if variable is 'undefined' or 'null'. Even though I found my solution it raised more questions that I couldn't find the answer for within the sea of "answers".
The first solution that has 910 upvotes uses typeof
, but this didn't work for me:
var username = prompt("Choose a username:");
if (typeof username === 'undefined'){
alert("Username is required!");
} else {
console.log("Your username is: " + username);
}
It also states a shorter version, which did work for me:
var username = prompt("Choose a username:");
if (!username){
alert("Username is required!");
} else {
console.log("Your username is: " + username);
}
Another answer caught my eye as it included a part of my personal code username === null
, which has 319 upvotes, but this didn't work for me either:
var username = prompt("Choose a username:");
if (username === undefined || username === null) {
alert("Username is required!");
} else {
console.log("Your username is: " + username);
}
An edit to the answer also states that using just username === null
is sufficient.
So my question is why does !username
work with that specific code but the others did not?