324

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) {...}
Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
nickb
  • 8,430
  • 11
  • 34
  • 46
  • Possible duplicate of [How do you check for an empty string in JavaScript?](https://stackoverflow.com/questions/154059/how-do-you-check-for-an-empty-string-in-javascript) – T.Todua Dec 04 '18 at 09:32

9 Answers9

443

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
Tim Down
  • 292,637
  • 67
  • 429
  • 506
82

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

Tolgahan Albayrak
  • 1,519
  • 1
  • 11
  • 13
  • 1
    In case for those wondering... This does not check for an empty string `("")` and undefined. See my fiddle as reference: https://jsfiddle.net/b0tm7yaf/ – Barrosy Jan 18 '19 at 15:25
49

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.

Jonathon Bolster
  • 15,221
  • 3
  • 39
  • 46
  • 36
    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. – Werzi2001 Sep 19 '13 at 16:03
  • 2
    the link no longer works. I found a copy of what appears to be the post here: http://appendto.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/ 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... – thepaulpage Jul 15 '15 at 15:05
  • 2
    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. – apraetor Nov 22 '16 at 18:02
  • This will not work if value present but is 0 (zero) – zmechanic Mar 23 '20 at 10:26
32
  • 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

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
10

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.

Flat Cat
  • 789
  • 4
  • 12
  • 21
  • 1
    Rather parse your value than comparing against `null` strings. – Bergi Mar 03 '15 at 14:56
  • 1
    This answer is legitimate, whether or not you understand the application of it. I don't appreciate being downvoted for posting things that actually worked. Did you notice it had an upvote before you touched it? That's because it is a real scenario. – Flat Cat Mar 03 '15 at 17:32
  • 5
    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 – Bergi Mar 03 '15 at 17:41
  • 2
    Apparently you don't understand. I realize you think you do, but you don't. – Flat Cat Mar 03 '15 at 22:09
  • 5
    I do understand that it was a working solution. But I don't think it is good advice, so please respect my downvote. – Bergi Mar 03 '15 at 22:18
2

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
}
OpenUser
  • 49
  • 1
  • 5
1

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

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

Sanjay Kumaar
  • 530
  • 5
  • 13
1

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) { }
D. Schreier
  • 1,462
  • 1
  • 17
  • 29
hoogw
  • 3,560
  • 1
  • 26
  • 28
-4

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.

THE DOCTOR
  • 4,095
  • 10
  • 40
  • 60
  • 13
    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? – Tim Down Dec 05 '10 at 22:29
  • 1
    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. – THE DOCTOR Dec 05 '10 at 22:34