Table of contents
Short-circuiting is a feature of the logical operators &&
(AND) and ||
(OR) that allows them to return a value without evaluating the whole expression. This can improve the efficiency and speed of evaluating a condition or expression.
In JavaScript when an expression or condition with multiple parts connected by logical operators are being evaluated short-circuiting allows allows the program to stop or "short-circuit" the evaluation as soon as the outcome is determined.This means that if the result can be determined by only evaluating a portion of the condition or expression , the program won't waste time evaluating the rest.
Now let’s see how it works for the two main logical operators:
1.Logical AND (&&):
If the left operand is falsy(false), the entire expression is false. In this case, there's no need to evaluate the right operand but if the first operand is truthy(true), it returns the right operand.
Let’s see some examples in code…
console.log(false && false) // Output: false
console.log(true && false) // Output: false
console.log(false && true) // Output: false
console(null && true) // returns null
console.log(undefined && false && true) // Output: undefined because it is a flasy value in javascript , wont bother to evaluate the rest of the code
console.log(true && 'This is a string') // Output: 'This is a string' because the first value is truthy the expression then moves to evaluate the right operand
2.Logical OR (||):
This operator does the opposite of the && operator i.e If the left operand is truthy(true), the entire expression is true. In this case, there's no need to evaluate the right operand but if the first operand is falsy(false), it returns the right operand.
Let’s see some examples in code…
console.log(false || 'This is a string'); // Output: 'This is a string'
console.log(true || 'This is a string'); // Output: true
console.log(true || false) // Output: true
console.log(false || true) // Output: true
console.log(false|| 0 ) // Output: 0 because the first value is falsy , the expression then moves to evaluate the right operand
that'll be all for this article , you can check out the resources below to understand more on truthy and falsy values in javascript
👉Truthy Values
👉Falsy Values