Compare 3 Values in JavaScript #
To compare 3 values, use the logical AND [&&] operator to chain multiple conditions. When using the logical AND [&&] operator, all conditions have to return a truthy value for the if
block to run.
Copied!
const value1 = 10; const value2 = 10; const value3 = 10; if [value1 === value2 && value2 === value3] { // 👇️ this runs console.log['✅ all 3 values are equal']; } else { console.log['⛔️ values are NOT equal']; }
In the code example, we used the logical AND [&&] operator to chain two conditions.
When using the logical AND [&&] operator in an if
statement, all conditions have to be met for the if
block to run.
The logical AND [&&] operator returns the value to the left if it's falsy, otherwise it returns the value to the right.
The falsy values in JavaScript are: false
, null
, undefined
, 0
, ""
[empty string], NaN
[not a number]. All other values are truthy.
This means that if the conditions on both sides of the logical AND [&&] operator evaluate to a value other than the aforementioned 6, the if
block is run.
If our example we check if the 3 values are equal. Since the conditions on both sides of the operator return true
, the if
block
is run.
First, the condition on the left of the &&
is evaluated, if it returns a falsy value, the condition on the right-hand side is not evaluated at all and the else
block is run.
Let's look at another example.
Copied!
const value1 = 10; const value2 = 10; const value3 = 20; if [value1 === value3 && value2