DEV Community

Manav Misra
Manav Misra

Posted on

Logical Operators and Short Circuit Assignment

Logical Operators and Short Circuiting

In many programming languages, we denote 'and' with: && and 'or' with ||.

&&

&& expects both the left and the right hand side operands to be true for the entire expression to evaluate to true. For example, roomCleaned && dishesWashed requires both a 'clean room' and 'dishes washed' for the whole expression to be true. If either of those are false, the entire expression returns false.

Furthermore, 👆🏽, if roomCleaned is false, there is no reason to bother checking dishesWashed. If the left-hand side operand is false, we are *short circuited. JS will not evaluate the right-hand side operand.

||

|| only requires one of the operands to be true for the entire expression to return true. For example, roomCleaned || dishesWashed only needs either operand to be true. As long as either of those is true, the entire expression returns true.

Furthermore, 👆🏽, if roomCleaned is true, there is no reason to bother checking dishesWashed. If the left-hand side operand is true, we are *short circuited.* JS will not evaluate the right-hand side operand.

'falsey' and 'truthy'

When working with 'non-boolean' operands, logical operators will treat them as 'falsey' or 'truthy.' For example, "" is 'falsey,' as is 0. "a" or 1 are 'truthy.' In essence, JS treats 'empty-ish' or null-ish things as 'falsey.'

Combining this with the short circuiting:

    // 'or' Short Circuit! - "a" is 'truthy', so no need to for '333'
    "a" || 333; // a

    const a = "";
    // 'a' is bound to a 'falsey' empty STRING, so we 'take' 'truthy' '333'. 
    a || 333; // 333

    null || "hello"; // hello

    // "a" is 'truthy,' but still must look at '333'
    "a" && 333; // 333

    // 'and' Short Circuit! - is 'falsey' - don't bother with '333'.
    0 && 333; // 0 

    // 'and' Short Circuit! - 'null 'falsey' - don't bother with 'hello'.
    null && "hello"; // null
Enter fullscreen mode Exit fullscreen mode

Short Circuit Assignment

Although use cases for && short-circuiting are virtually non-existent, we can use || short-circuiting to avoid having 'blank' for 'falsey' values in our data. The concept is the same as we saw 👆🏽, but we are just combining that with variable assignment.

    // Imagine user left form field blank - no FORM VALIDATION.
    // We can assign a default value so that we can still 'accept' the 'form,' but it's clear that the user left that blank.
    const userName = "" || "Blank form field";

    // Imagine that we retrieved some product from database as an OBJECT LITERAL.
    const someProduct = { 
        name: "Great Widget",
        price: 0 // Bad data entry - no database validation! 😱
    }

    // We can prevent '0' from being shown to user.
    const displayedPrice = someProduct.price || "Please Call For Price!"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)