373

I know that below are the two ways in JavaScript to check whether a variable is not null, but I’m confused which is the best practice to use.

Should I do:

if (myVar) {...}

or

if (myVar !== null) {...}
1

10 Answers 10

486

They are not equivalent. The first will execute the block following the if statement if myVar is truthy (i.e. evaluates to true in a conditional), while the second will execute the block if myVar is any value other than null.

The only values that are not truthy in JavaScript are the following (a.k.a. falsy values):

  • null
  • undefined
  • 0
  • "" (the empty string)
  • false
  • NaN
Sign up to request clarification or add additional context in comments.

Comments

100

Here is how you can test if a variable is not NULL:

if (myVar !== null) {...}

the block will be executed if myVar is not null.. it will be executed if myVar is undefined or false or 0 or NaN or anything else..

1 Comment

In case for those wondering... This does not check for an empty string ("") and undefined. See my fiddle as reference: jsfiddle.net/b0tm7yaf
60
  • code inside your if(myVar) { code } will be NOT executed only when myVar is equal to: false, 0, "", null, undefined, NaN or you never defined variable myVar (then additionally code stop execution and throw exception).
  • code inside your if(myVar !== null) {code} will be NOT executed only when myVar is equal to null or you never defined it (throws exception).

Here you have all (src)

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

Comments

53

Have a read at this post: http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/

It has some nice tips for JavaScript in general but one thing it does mention is that you should check for null like:

if(myvar) { }

It also mentions what's considered 'falsey' that you might not realise.

4 Comments

This check is actually not safe. If myvar is 0, false or any other falsy value the test will fail (if you only intend to check for not null). So only use this to check for not null if the variable can never have another falsy value.
the link no longer works. I found a copy of what appears to be the post here: appendto.com/2010/10/… It's strange though, because Elijah's post (and the sample code) would suggest that he's the author, but he's not listed as the author there...
Looks like that site no longer exists. It would be helpful if you could include the information in the post itself, rather than just an external link.
This will not work if value present but is 0 (zero)
9

There is another possible scenario I have just come across.

I did an ajax call and got data back as null, in a string format. I had to check it like this:

if(value != 'null'){}

So, null was a string which read "null" rather than really being null.

EDIT: It should be understood that I'm not selling this as the way it should be done. I had a scenario where this was the only way it could be done. I'm not sure why... perhaps the guy who wrote the back-end was presenting the data incorrectly, but regardless, this is real life. It's frustrating to see this down-voted by someone who understands that it's not quite right, and then up-voted by someone it actually helps.

5 Comments

Rather parse your value than comparing against null strings.
yes, and I downvoted because I think it's the wrong solution. In the case of an ajax call, you should better do value = JSON.parse(value) and then use the simple and proper value != null test
I do understand that it was a working solution. But I don't think it is good advice, so please respect my downvote.
I downvote because != 'any-thing-you-want' ALSO returns true !!! You have the result you want but it doesn't actually handle the cases you want :)
@FlatCat Please note that down voting is not a personal criticism of you and others up-votes are not relevant in this context. it is purely about this answer being useful and helpful to others in the voters opinion.
5

if (0) means false, if (-1, or any other number than 0) means true. following value are not truthy, null, undefined, 0, "" (empty string), false, NaN

never use number type like id as

if (id) {}

for id type with possible value 0, we can not use if (id) {}, because if (0) will means false, invalid, which we want it means valid as true id number.

So for id type, we must use following:

if ((Id !== undefined) && (Id !== null) && (Id !== "")) {

} else {

}

for other string type, we can use if (string) {}, because null, undefined, empty string all will evaluate at false, which is correct.

if (string_type_variable) { }

1 Comment

If 0 is the only case that does not fit into the if (id) {} scenario, you can always do something like if (id || id === 0) which is more concise than your solution and should work the same.
3

Sometimes if it was not even defined is better to be prepared. For this I used typeof

if(typeof(variable) !== "undefined") {
    //it exist
    if(variable !== null) {
        //and is not null
    }
    else {
        //but is null
    }
}
else {
    //it doesn't
}

Comments

1

if myVar is null then if block not execute other-wise it will execute.

if (myVar != null) {...}

1 Comment

Not the string 'null', but the special value null.
-2

Rather than using multiple condition statements you can use below solution.

if(![false, 0, "", null, undefined, NaN].includes(myVar)){

   // It's not a null value

}

1 Comment

This answer was flagged as Low Quality. Please read How do I write a good answer?. While this code block may answer the OP's question, this answer would be much more useful with some explanation. Explain what it does, and how it's different / better than existing answers.
-5

The two conditional statements you list here are not better than one another. Your usage depends on the situation. You have a typo by the way in the 2nd example. There should be only one equals sign after the exclamation mark.

The 1st example determines if the value in myVar is true and executes the code inside of the {...}

The 2nd example evaluates if myVar does not equal null and if that case is true it will execute your code inside of the {...}

I suggest taking a look into conditional statements for more techniques. Once you are familiar with them, you can decide when you need them.

2 Comments

That probably isn't a typo in the second example. That second = is crucial and makes a huge difference to the question. Perhaps you're not aware of the existence of !== and === operators in JavaScript?
Thanks for pointing that out. I immediately thought it was a typo, but now recall that which I have not seen in a while and had forgotten about.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.