How to check if a variable is not null?

How to check if a variable is not null?

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) {…}

Solutions/Answers:

Solution 1:

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
  • "" (the empty string)
  • false
  • NaN

Solution 2:

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 or NaN or anything else..

Related:  How do I print part of a rendered HTML page in JavaScript?

Solution 3:

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.

Solution 4:

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.

Related:  Simple ng-include not working

Solution 5:

Here you have all (src):

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

So

  • 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).

Solution 6:

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

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