Check if Multiple Variables are Not NULL in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 24, 2022

banner

Photo from Unsplash

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 used the && (and) operator to check if both variables are not equal to null.

For the if block to run, both 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.

The && operator returns the value to the left if it's falsy, otherwise the value to the right is returned.

Falsy values in JavaScript are: undefined, null, NaN (not a number), "" (empty string), false and 0.

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.