Buy Me A Coffee 😇

Short-Circuit Evaluation

/ It is always awesome to use a quick way to write simple like a ternary operator.

#short-circuit
#javascript
✍️ BroJenuel
Mar. 08, 2023. 2:08 PM

It is always awesome to use a quick way to write simple like a ternary operator.

// example 1:
let x = 3;

let answer = x > 5 ? true : false; // false since 3 is less than 5

// example 2:
let y = [1,2,3];
let z = [4,5];

let answer = y.includes(5) ? (z.includes(5) ? true : false) : false; // true

The ternary operator is good to use but not always. So JavaScript introduced a way to evaluate expressions. These are && (AND) and || (or).

How Does it Work?

1. && - this will return the first falsy value. If all are true, return the last value;

console.log(5 && 6 && null && false && 0);
/** 
result: null 
- because the null is the first `falsy`.
*/

console.log(true && 1 && 4); 
/** 
result: 4 
- because everything is `truthy`. 
*/

let a = [1,2,3].includes(3) && 5 && 'good';
/**
result: 'good'
- because everything is truthy
*/

2. || - next is the || operator. Using || will return the first true or ‘truthy’ value. If every operand evaluates to false , the last evaluated expression will be returned.

console.log(5 || 6 || null || false || 0);
/** 
result: 5
- because the 5 is the first `truthy`.
*/

console.log(false || 6 || null || false || 0);
/** 
result: 6
- because the 6 is the first `truthy`.
*/

console.log(true || 1 || 4); 
/** 
result: true 
- because true is thruthy. 
*/

let a = [1,2,3].includes(3) || 5 || 'good';
/**
result: true
- because the first condition is truthy.
*/

This is very useful to make conditional statements smaller. Something Like This:

    if (data) {
        return data;
    } else {
        return 'No Data';
    }

can be converted to:

return (data || 'No Data');

If you enjoy this article and would like to show your support, you can easily do so by making a donation through Ko-fi. Your contribution is greatly appreciated!

Buy Me a Coffee at ko-fi.com
@ BroJenuel