3

I have a null variable that is behaving weird. For some reason I can't seem to detect whether or not it is null! The var is called emailFromUrl.

   console.log(emailFromUrl); //returns null
   console.log(emailFormUrl.toString()); //returns null
   console.log(emailFromUrl === null); //false!
   console.log(emailFromUrl != null); //true!
   console.log(typeof emailFromUrl); //string
   console.log(!emailFromUrl); //false!
   console.log(emailFromUrl === ""); //false

What the heck is going on here?

The answer:

   console.log(emailFromUrl === 'null'); //true!

The unfiltered console log:

Test71 | emailFromUrl : null | emailFromUrl === null : false | emailFromUrl != null : true | emailFromUrl.toString() : null | typeof emailFromUrl : string | !emailFromUrl : false | emailFromUrl === "" : false | emailFromUrl === "null" : true
19
  • What happens if you run this console.log(typeof emailFromUrl); ? Commented Jun 8, 2012 at 15:51
  • You last log clearly shows it is not equal to null. Commented Jun 8, 2012 at 15:51
  • What kind of null are you talking about? Do you mean you've defined it but it's undefined? var emailFromUrl or that it's defined as null var emailFromUrl = '' Commented Jun 8, 2012 at 15:52
  • As far as I can tell, console.log(...) returns undefined. Your string is probably empty. Nothing prints out, it's not null, it is not null, and it has a type of string. Sounds like an empty string. Commented Jun 8, 2012 at 15:54
  • 2
    @PitaJ. I got the feeling, if all the lines are right, he's getting "null" instead of null. Commented Jun 8, 2012 at 16:04

3 Answers 3

6

Perhaps emailFromurl value is just a literal null string? ) That will explain all the results you get in your question, I think.

Sign up to request clarification or add additional context in comments.

1 Comment

It's easy actually: if emailFromUrl is truthy value (and it is, as its negation is false) and it's a string, there's only one value which will give 'null' when stringified - yep, 'null' itself. )
1

well the === operator checks the value and type. emailFromUrl is of type string not null which it why it evaluates to false there.

1 Comment

Oh also, do a check to see if it is undefined, i.e. emailFromUrl == undefined
0

Unless you want specific logic based on it being null, you can check if the object is "falsy" (if the object is undefined, 0 or null)

if(!emailFromUrl) {
    // handle the null scenario
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.