Check if Multiple Variables are Not NULL in JavaScript

avatar

Borislav Hadzhiev

Fri Oct 15 20212 min read

banner

Photo by Zalmen Pollak

Check if Multiple Variables are Not Null #

To check if multiple variables are not null in JavaScript, use the && (and) operator to chain multiple conditions. When used with boolean values the && operator only returns true if both conditions are met.

index.js
const a = 1; const b = 2; if (a !== null && b !== null) { console.log('โœ… neither variable is null'); } else { console.log('โ›”๏ธ at least one of the variables is null'); }

We use the && (and) operator to check if both variables are not equal to null.

For the if block to run, both of the conditions have to be satisfied.

If the else block runs, at least one of the variables is equal to null.

The && operator is evaluated left to right. If the first condition in our if statement returns false, the operator short-circuits and doesn't evaluate the second condition.

For example, in the following if statement, the 5 > 1 condition is never evaluated.

index.js
if (null !== null && 5 > 1) { }

We first check if null !== null and get a value of false, so the && operator short-circuits.

Here are some more examples of using the && (and) operator.

index.js
console.log(true && true); // ๐Ÿ‘‰๏ธ true console.log(true && null); // ๐Ÿ‘‰๏ธ null console.log(null && true); // ๐Ÿ‘‰๏ธ null console.log('test' && 'hi'); // ๐Ÿ‘‰๏ธ 'hi' console.log('test' && ''); // ๐Ÿ‘‰๏ธ '' console.log('' && 'hi'); // ๐Ÿ‘‰๏ธ ''

The && operator returns the value of one of the operands.

If the first value we pass to it is a falsy value, it returns the first value, otherwise it returns the second.

Falsy values in JavaScript are: undefined, null, NaN, empty string, false and 0.

In our last example, because we used an empty string as the first value and an empty string is falsy, it got returned from the && operator.

In short, if the value to the left is falsy, it gets returned from the && operator. In all other cases the operator returns the value to the right.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee