Borislav Hadzhiev
Fri Oct 15 2021·2 min read
Photo by Zalmen Pollak
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.
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
.
&&
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.
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.
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, we used an empty string as the first value and an empty
string is falsy, so 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.