DEV Community

Jenuel Oras Ganawed
Jenuel Oras Ganawed

Posted on

2 2

Short-Circuit Evaluation

It is always awesome to use a quick way to write simple like 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
Enter fullscreen mode Exit fullscreen mode

Ternary operator is good to use but not always. So javascript introduced a way to evaluate expressions. This 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
*/
Enter fullscreen mode Exit fullscreen mode

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.
*/
Enter fullscreen mode Exit fullscreen mode

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

    if (data) {
        return data;
    } else {
        return 'No Data';
    }
Enter fullscreen mode Exit fullscreen mode

can be converted to:

return (data || 'No Data');
Enter fullscreen mode Exit fullscreen mode

thanks for Reading Short Reads. If you like to donate, click the image.

Buymecoffee Donate to Bro Jenuel

Retry later

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more