Short-Circuiting with the Logical && and || Operators in JavaScript
In JavaScript, every value is either "truthy" or "falsy" when evaluated in a strictly Boolean context. Values that evaluate to "true" are considered "truthy", and values that evaluate to "false" are considered "falsy". Strings of one or more characters, numbers (positive or negative) other than zero, and arrays holding zero or more values are all considered to be "truthy". "Falsy" values include zero, empty strings, the "null" value, "undefined" and "NaN".
Short-circuiting in JavaScript is a behavior exhibited by logical operators (&&, ||) where the evaluation of the second condition is skipped if the outcome can be determined by evaluating the first condition alone. The && operator returns the first "falsy" condition, or the last "truthy" condition if all conditions are truthy. The || operator returns the first "truthy" condition, or the last "falsy" condition if all conditions are "falsy".
Here are some examples:
const value = 0 const result = value && "Truthy value" console.log(result) // Output: 0
The "value" evaluates to 0, which is "falsy", so the expression short-circuits and the second condition ("Truthy value") is never evaluated.
Here's an example of a "truthy" evaluation:
const value = "Hello" const result = value && "Truthy value" console.log(result) // Output: "Truthy value"
In this example, "value" is set ot a non-empty string, which is a "truthy" value. Hence the second condition "Truthy value" gets returned in the console, since it's the last "truthy" condition.
The || operator returns the first "truthy" condition, or the last "falsy" condition if all conditions are "falsy":
const name = "" const displayName = name || "Guest" console.log(displayName) // Output: Guest
"name" is an empty string, which is a "falsy" value. The second condition is evaluated, and "Guest" is assigned to "displayName".
const name = "Mary" const displayName = name || "Guest" console.log(displayName) // Output: "Mary"
"name" is a non-empty string, which is "truthy", so the first condition "Mary" gets returned, as it is the first "truthy" condition.