Borislav Hadzhiev
Mon Oct 18 2021·2 min read
Photo by Taylor Nicole
To check if a variable is not equal to multiple values:
const a = 'one'; const b = 'two'; const c = 'three'; if (a !== b && a !== c) { console.log('✅ a is not equal to b and c'); } else { console.log('⛔️ a is equal to b or c, or both'); }
We used the
strict inequality (!==)
operator to check if the variable a
is not equal to the variables b
and c
.
The operator returns a boolean result:
true
if the values are not equalfalse
if the values are equalTo chain the two conditions we used the logical and (&&) operator.
The if
block would only run if both conditions return true
.
&&
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.If the a !== b
part of the condition returns false
, the a !== c
part is
not evaluated at all.
For example, in the following if
statement, the 10 > 1
condition is never
evaluated.
if (5 > 50 && 10 > 1) { }
We first check if 5 > 50
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 && false); // 👉️ false console.log(false && true); // 👉️ false console.log('abc' && 'hello'); // 👉️ 'hello' console.log('hello' && ''); // 👉️ '' console.log('' && 'hello'); // 👉️ ''
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.