logical operators in JavaScript
Logical operators are used when doing comparisons of boolean values. If Booleans are being used as operands it will either return true or false. If non-boolean values are used for operands if will return one of the specified operands. The logical operators look like (||)
, (&&)
and (!)
.
The OR and AND operators are short circuited
When logical operators (||)
and (&&)
are being evaluated it tests for a “short circuit” which means as soon as one of the values is true for the OR operator or if one the values is false for the AND operator it will stop and return the value.
false && (anything)
is short-circuit evaluated to false.
true || (anything)
is short-circuit evaluated to true.
anything means any value.
how logical AND works (&&)
(&&)
will return the first expression if it is a falsy value otherwise the second expression will be returned.
JavaScript
false && false; // false
"" && false; // ""
false && ""; // false
(1 === 3) && false; // false
// first expression evaluated to a falsy value
2 && ""; // ""
First expression evaluated to true so it had to evaulate the second expression and it was false.
2 && 3; // 3
First expression and second expression evaluated to true so it returned the last expression that was evaluated.
how logical OR works (||)
(||)
will return the first expression if its a truthy value otherwise the second expression will be returned.
JavaScript
(1 === 3) || false; // false
// first and second expression are falsy values
false || undefined; // undefined
// first and second expression are falsy values
true || false; // true
// first expression evaluated to a truthy value
"Lime" || "Lemon"; // "Lime"
// first expression evaluated to a truthy value
false || 1000; // 1000
// second expression evaluated to a truthy value
how logical NOT works (!)
Logical NOT
converts the expression into a boolean and inverts the boolean.
JavaScript
!true; // false
!false; // true
!"Lime"; // false
!1000 // false
conclusion
(&&)
and (||)
operators are used in conditions.