Coder Perfect

What’s the best way to tell if a variable isn’t null?

Problem

I know there are two techniques to check whether a variable is not null in JavaScript, but I’m not sure which is the best practice.

Should I do:

if (myVar) {...}

or

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

Asked by nickb

Solution #1

They are not interchangeable. If myVar is truthy (i.e. evaluates to true in a conditional), the first will run the block after the if statement, whereas the second will execute the block if myVar has any value other than null.

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

Answered by Tim Down

Solution #2

Here’s how to make sure a variable isn’t NULL:

if (myVar is not null)…

If myVar is not null, the block will be run. If myVar is undefined, false, 0 or NaN, or anything else, the block will be executed.

Answered by Tolgahan Albayrak

Solution #3

See http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/ for more information.

It includes several useful recommendations about JavaScript in general, but it does mention that you should check for null, as in:

if(myvar) { }

It also explains what is called ‘falsey,’ something you may not be aware of.

Answered by Jonathon Bolster

Solution #4

You can find everything you need here (src)

if

(its negation!=) ===================

(its negation!==) ======================

Answered by Kamil Kiełczewski

Solution #5

I’ve now came across another conceivable possibility.

I made an ajax request and received null data in a string format. I have to double-check it as follows:

if(value != 'null'){}

So, rather than being null, null was a string that read “null.”

EDIT: It’s important to note that I’m not promoting this as the way things should be done. This was the only way I could get it done in one circumstance. I’m not sure why… maybe the guy who created the backend presented the data incorrectly, but whatever the case, this is real life. It’s aggravating to see this downvoted by someone who recognizes that it’s not quite right, and then upvoted by someone who can genuinely benefit from it.

Answered by Flat Cat

Post is based on https://stackoverflow.com/questions/4361585/how-to-check-if-a-variable-is-not-null