39Undefined39 or 39Null39 Variable in JavaScript

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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);
}

http://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or-null http://stackoverflow.com/questions/2647867/how-to-determine-if-variable-is-undefined-or-null

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?

Answers

When you are prompted for a username and don t type in anything, the value stored is an empty string, . This equals the value false in JavaScript.

The reason why the typeof(username) == undefined one didn t work is because the username variable was declared in the previous line. As I mentioned above, the type of username is a string, even if nothing was typed in.

And yes, to check if a variable is undefined, use typeof varName === undefined.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/32892124/undefined-or-null-variable-in-javascript

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils