Have you ever written code like this?
1 2 3 4 5 6 7 8
Logical OR Operator
The logical OR operator returns the first true value it finds (looking from left to right). If nothing is true in the statement, then it defaults to the last value (false in the previous code example). This makes it perfect for setting default values.
undefined - Returns false.
null - Returns false
0 - Returns false. All other numbers return true.
Here is a more advanced (and more common) use case for the logical OR operator. You want to check if a certain string value is empty, and if it is, you want to set a variable to a default value of “test”
Here is the breakdown of how the above code works:
1. If the somethingElse value is both a string and is true (is not empty), then set the something variable equal to the somethingElse value. It is important to check that the somethingElse value
typeof evaluates to
string, because we want to make sure we are dealing with a string (and not an integer such as 0 which will evaluate to true).
2. If the somethingElse value is not a string and is false (is empty), then set the something variable equal to “test”.
Logical AND Operator
If the somethingElse value evaluates to false, then the something variable gets set to the somethingElse value. If the somethingElse variable evaluates to true, then the something variable gets set to “something”. The logical AND operator uses the exact opposite logic of the logical OR operator.