Question

I want to check the null value in JavaScript.

For instance, test() is function which could return null. So If I want to test the null check efficiently what should be my approach.

var a = test();

followed by

if (a) {}

OR

if (a !== null) {}

? since if (a) will check for null, undefined, false, 0, NaN which might not be the best approach when we know we could get only null value.

Was it helpful?

Solution

To check null only

if (value !== null) {
}

If you want to check even for 'undefined'

if (typeof value !== 'undefined' && value !== null)

I will recommend you to check both undefined and null value.

function test() {
  var a;
  return a;  // returns undefined
}

function test() {
  var a = null;
  return a;  // returns null   
}

So there is a possibility that value can undefined or null. So better to check both.

OTHER TIPS

As you pointed out, different methods check for different things and you need to choose the most suitable one depending on your needs. The differences in performance between them are minuscule and certainly not worth micro-optimizing against.


if (a)

Ensures a truthy value. This might not be what you wanted if a return value of 0 or '' is actually valid.


if (a !== null)

Ensures a null returned value is filtered.


if (a !== null && a !== undefined)

Ensures a null or undefined value is filtered.


if (a != null)

Same as the previous one, filters out null and undefined values. It is shorter, but certain coding styles enforce strict equality checks and a careless maintainer could inadvertendly change the logic by "fixing" it.


var a = test() || default;

Not exactly a check, but very useful because it doesn't branch your logic. When a certain default value can be applied if the result of the test() call is falsy, you might want to use this to avoid the if alltogether and have a clear code path.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top