-2

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?

Community
  • 1
  • 1

3 Answers3

2

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.

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
0

in javaScript if a variable is undefined then that means it is != null. if one variable is null and second is undefined than result for == will be true and for != will be false

dinesh.kumar
  • 167
  • 1
  • 10
-1

Try:

typeof username === 'undefined'

Instead of:

username === undefined

if you try:

typeof username === undefined

Will fail too.

Javascript :-)

Sergeon
  • 6,638
  • 2
  • 23
  • 43