How does { (some falsy expression) && expr } work?

How to show and hide components, tag elements the easy way.

Hello there lovely people!

I was working on a project and I had a problem, I wanted to hide and show a component when I click a button. When I was working on JavaScript, I used to just add and remove a class called ‘.hide’ that contained (display: none;) from the element, and it worked just fine.

But in React, even though I could’ve done the same thing, I was searching for a better solution. And I found the answer on the most valuable thing in our lives, Google:

Peter Griffin typing

The answer is to use useState, and make a function that changes that state from true to false, just like the example below:

import React, { useState } from 'react'

function Example() {

{isOn, setIsOn} = useState(true)

//here we change the value of isOn to true if it's false, and vice versa
const toggleOnOff = () => {

    if (isOn === true) 
          setIsOn(false)

     } else if (isOn === false) {
          setIsOn(true)
     }
}

  return (
    <div>
            {/* if toggleOnOff is true, it will show 'On' */}
            {toggleOnOff && <h1>On</h1>

            {/* if toggleOnOff is false, it will show 'Off' */}
            {!toggleOnOff && <h1>Off</h1>

            <button onClick={toggleOnOff}>Toggle</button>
        </div>
  )
}

export default Example

And it worked!

At first, I didn’t understand how does it work. And now that I have work to do, obviously I have to distract myself. I looked into it and I’ll show you how it works.

First, Truthy and falsy values

Truthy value is a value considered to be true when is encountered in a boolean context. And a Fulsy value is a value considered to be false when is encountered in a boolean context.

The majority of values are truthy, because all values are truthy, except when they are falsy (duh).

What are the falsy values?

  • false
  • 0
  • -0
  • 0n
  • ""
  • null
  • undefined
  • and NaN

Examples of truthy values (they all true, so the IF block will be executed):

  • if (true)
  • if ({})
  • if ([])
  • if (42)
  • if ("0")
  • if ("false")
  • if (new Date())
  • if (-42)
  • if (12n)
  • if (3.14)
  • if (-3.14)
  • if (Infinity)
  • if (-Infinity)

Short-circuit Evaluation?

We all know the operators AND( && ), OR( || ), and NOT ( ! ), I’m not going to go deep into them, but I’ll explain what does short-circuit evaluation means, it basically means that when JavaScript evaluates an OR expression for example, it will look at the first operand, and if it’s true, JavaScript will not even look at the second operand, and it will execute whatever next:

const T = true;
const F = false

//if T = true, JavaScript will ignore F and it'll execute the IF block.
if (T || F) {
        console.log(T);
};
//expected output: true

In a situation when we have an AND expression, JavaScript will look at the first operand, and if it’s false it will not look at the second operand, and it will NOT execute the code next of it (if you find it hard to understand the logical operators, click here):

const T = true;
const F = false

//if F = false, JavaScript will ignore T and it will execute the ELSE.
if (F && T) {

//this code will NOT be executed
    console.log(T);

} else {
    console.log(F);
};

//expected output: false

That’s how it works!

let’s go back for our previous example:

import React from 'react'

function Example() {

{isOn, setIsOn} = useState(true)

//here we change the value of IsOn to true if it's false vice versa
const toggleOnOff = () => {

    if (isOn === true) 
          setIsOn(false)

     } else if (isOn === false) { 
          setIsOn(true)
     }
}

  return (
    <div>
            {/* if toggleOnOff is true, it will show 'On' */}
            {toggleOnOff && <h1>On</h1>

            {/* if toggleOnOff is false, it will show 'Off' */}
            {!toggleOnOff && <h1>Off</h1>

            <button onClick={toggleOnOff}>Toggle</button>
        </div>
  )
}

export default Example

As I explained before, JavaScript sees the AND expression in {toggleOnOff && <h1>On</h1> , and start evaluate the expression, it sees the first operand, if it’s true, it will execute the code after. If it’s false, it’ll skip it.

And that’s how it works, it helped me a lot in my project, and I thought it might be helpful for others.

Tip: You cannot have more than one tag element in the expression:

{toggleOnOff && <h1>First tag</h1> <h2>Second tag</h2>} ❌

As long as there is one parent it will work, you can use <div> or <></>:

{toggleOnOff && <> <h1>First tag</h1> <h2>Second tag</h2> </>} ✅

Thank you for your time ❤️

Resources: