The and-operator (&&
) and the or-operator (||
) employ short-circuiting to prevent unnecessary work if the outcome of the operation does not change with the extra work.
In x && y
, y
will not be evaluated if x
evaluates to false
, because the whole expression is guaranteed to be false
.
In x || y
, y
will not be evaluated if x
evaluated to true
, because the whole expression is guaranteed to be true
.
Example with functions
Take the following two functions:
function T() { // True
console.log("T");
return true;
}
function F() { // False
console.log("F");
return false;
}
Example 1
T() && F(); // false
Output:
‘T’ ‘F’
Example 2
F() && T(); // false
Output:
‘F’
Example 3
T() || F(); // true
Output:
‘T’
Example 4
F() || T(); // true