Logical operators are most commonly used in JavaScript where the value of evaluated expressions are shared to come to a decision; these expressions may also be evaluated as not true, or in an either-or condition. As such, they’re often associated with if
statements.
Logical AND: &&
Compares two conditions and returns a true
or false
summary. In the context of an if
:
var x = 5;
var y = "Monday";
if (x > 3 && y == "Monday") {
console.log("Success!");
}
The expressions are evaluated from left to right; both the expressions must return true
in order for the Success!
statement to be executed. If either is false
, the if
will be ignored, and “Success!” will never be written to the console. That is:
Left | Right | Result |
---|---|---|
true | true | TRUE |
true | false | FALSE |
false | true | FALSE |
false | false | FALSE |
Logical OR: ||
In an OR
comparison, any evaluation that is true will trigger conditional code:
var a = 16;
var b = "Slpadash";
if (a > 3 || b == "Exemplary") {
console.log("Success!");
}
In the example above, the second evaluation will never be true, but the first one will be. Because an OR
has been used, the console
code will be run.
Logical NOT: !
Works as a “not” in a comparison statement:
var c = true;
var d = 1979;
if (c == true && d !== 1980) {
console.log("Correct");
}
In the code above, Correct
will be printed out. The comparison would read as “if c
is true
and d
is not equal to 1980…”
!
can also be used by itself:
var c = false;
var d = 1979;
if (!c || d <> 1980) {
console.log("Correct");
}
The comparison would be read as “if c
is false or d
is greater or less than 1980”.
Conclusion
Logical operators are key to making complex decisions in JavaScript, and can be used in many different coding patterns, including ternary operators, which we’ll be looking at next.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.