Check if Variable Doesn't Equal Multiple Values in JS

avatar

Borislav Hadzhiev

Mon Oct 18 20212 min read

banner

Photo by Taylor Nicole

Check if Variable Doesn't Equal Multiple Values #

To check if a variable is not equal to multiple values:

  1. Use the logical and (&&) operator to chain multiple conditions.
  2. In each condition, use the strict inequality operator (!==) to check that the variable is not equal to the value.
  3. If all conditions pass, the variable is not equal to any of the values.
index.js
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 equal
  • false if the values are equal

To chain the two conditions we used the logical and (&&) operator.

The if block would only run if both conditions return true.

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.

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.

index.js
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.

index.js
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, 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