Logical OR (||) Expression

Summary

Evaluates from left to right. If the first expression evaluates to a truthy value, it is returned; otherwise, the evaluated value of the second expression is returned. This expression can be used to test more than one condition in if statements and other conditional statements.

Syntax

expression1 || expression2

Parameters

expression1
Any legal expression.
expression2
Any legal expression.

Description

|| is the logical OR operator. If the first expression evaluates to true (or a "truthy" value), it is returned; otherwise, the evaluated value of the second expression is returned. In the case of Boolean expressions, this yields the expected result of true if at least one of the expressions is true and false if both expressions are false. However, with other data types, the output may be non-Boolean. For example, false || "blue" yields "blue".

The || operator is evaluated from left to right.

Using || to test more than one condition in an if statement

The logical OR operator can be used to combine conditions and test if at least one condition is true, such as for if statements:

1
2
3
4
5
6
import System;
 
bool x = true, y = false;
if (x || y) {
    Console.log("One of 'x' or 'y' is true");
}

Short-Circuit Evaluation

If the expression prior to an || operator is true, then the expression is, if well-formed, true. In such cases JS++ does not evaluate the expression following ||.

While this "short-circuiting" is logically sound, it means that side effects of the expression after the operator are not executed. For example:

1
2
3
4
5
6
7
int x = 0, y = 0;
if ((3 > 2) || x++) { // does not iterate x because of short-circuiting
    y = 1;
}
(3 < 2) || x++; // iterates x
 
// final result is x = 1 (iterated once) and y = 1

Care must therefore be taken when the expressions following logical operators are expected to have side effects.

See Also

Share

HTML | BBCode | Direct Link