JavaScript check null or undefined – Best Practice

Let’s assume I have a variable called ‘a’ , which looks for some value.
var a;
if (a !== undefined && a!== null && a!=='') {
console.log("Something");
} else {
console.log("Nothing");
}

I have seen lot of developers is trying check condition like above to ensure we are getting the expected value we want.Do we really need to check the value a undefined and null and ?.

No. We don’t need.

Do like below as Best Practice

var a;
if (a) {
console.log("Something");
} else {
console.log("Nothing");
}

Did you understand what’s Javascript Engine doing under the hood?. In order to understand, Let’s analyze what will be the value return by the Javascript Engine when converting undefined , null and ”(An empty string also). You can directly check the same on your developer console.

You can see all are converting to false , means All these three are assuming ‘lack of existence’ by javascript. So you no need to explicitly check all the three in your code.

Also I want to point out one more thing

What will be the result of Boolean(0)?

Ofcourse false. This will create some bug on your code when 0 become a valid value on your expected result. So please make sure this thing also when you write the code