The logical OR operator

The logical OR operator (||) in JavaScript accepts two operands. If its left-side operand is truthy, then it will return that immediately; otherwise, it will evaluate and return the right-side operand:

0 || 1; // => 1
2 || 0; // => 2
3 || 4; // => 3

Much like the && operator, the || operator is flexible in that it does not cast what it returns to Boolean, and it evaluates in a short-circuited manner, meaning that it only evaluates the right-hand side operand if the left-side operand meets a condition—in this case, if the right-side operand is falsy:

true || thisWillNotExecute();
false || thisWillExecute();

Conventionally, a programmer may assume that the logical OR operator is akin to the question Are either A or B true? but in JavaScript, it is more akin to: If A is falsy, then give me B; otherwise, I'll settle for AIf we were to implement this operation ourselves, it might look something like this:

function or(a, b) {
if (a) return a;
return b;
}

Just as with &&, this means that || can be used flexibly to provide control flow or to evaluate specific expressions conditionally:

const nameOfUser = user.getName() || user.getSurname() || "Unknown";

As such, it should be used cautiously in a way that considers what readers of the code are familiar with, and in a way that considers all prospective operands and the resulting values from the operation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.187.178