
Irving Z. answered 07/05/19
Fullstack Software Engineer
What you're looking for is called short circuit evaluation. With the logical operators AND (&&) and OR ( || ), they are most commonly used in if statements but they also have another great use case.
Let's go over a few examples to understand how they work outside of if statements.
Let's say that you want to declare a variable based on if another variable exists or has a "truthy" value. You can do something like above which is called short circuit evaluation. Short circuit evaluation says when the && operator is used, the righthand side of the && statement is evaluated only if the lefthand side is true, otherwise the lefthand side is evaluated. In the example above, y equals 10 because x is true. Looking at the next example, a is false so therefore the righthand side of a && 10 is not evaluated so b is false.
The OR statement is the opposite. If the lefthand side is true, then it will get evaluated and not the righthand side. If it is false, then the righthand side will get evaluated. Here is a quick example:
If the concept is still a little fuzzy, here is the equivalent for the above code using if statements.