المعرفة:: JavaScript
الحالة::مؤرشفة
المراجع:: syahshiimi’s notes, The Complete JavaScript Course 2022 From Zero to Expert
There are two operators that allows us to perform shortcircuiting in JavaScript.
||
operator
&&
operator
How Does It Work?
- The
||
operator will return the first truthy value of all the operands or the last, if they are all falsy
- The
&&
operator will instead return the first falsy value of all the operands or the last, if they are truthy
| || | && |
---|
truthy | first | last |
falsy | last | first |
What Does Shortcircuiting Mean?
When the operators are applied in an operand, it returns the first value to whichever the statement follows the conditons of the operator.
Limitations
The operands will always read 0 as the falsy value. We can circumvent it with the Nullish coalescing operator.
Examples