Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript best practice to check only null values

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.

like image 459
djadmin Avatar asked Jan 22 '26 02:01

djadmin


1 Answers

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.

like image 103
Fizer Khan Avatar answered Jan 24 '26 19:01

Fizer Khan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!