Course contentsShow
← React
Lesson 113 of 2,3964. Conditional Rendering in JSXFree lesson

Safe Boolean Coercion: !! Pattern

Learn to use double negation `!!value` to safely convert numbers to booleans before &&.

Safe Boolean Coercion: !! Pattern

You'll learn how to prevent unexpected renders by forcing values to true/false before using &&.

The Problem We're Solving

Remember the "zero trap"? When you write {count && <div>Items</div>}, and count is 0, React renders that zero on the screen. That's because && returns the left side if it's falsy, and 0 is both falsy and renderable.

What !! Does

The double negation operator !! converts any value into an actual boolean (true or false). Here's how it works:

First ! (negation): Converts the value to boolean and flips it Second ! (negation again): Flips it back to the "correct" boolean

!!5      // true
!!0      // false (not rendered!)
!!""     // false
!!"hi"   // true

Safe Rendering Pattern

Instead of the risky {count && <Component />}, use:

{!!count && <Component />}

Now when count is 0, the !!0 becomes false, and React renders nothing instead of displaying zero.

Another Example

// Dangerous
{items.length && <p>You have items</p>}
// When items.length is 0, renders "0"

// Safe
{!!items.length && <p>You have items</p>}
// When items.length is 0, renders nothing

When to Use It

Anytime you're using && with a number, or any value where you're not 100% certain it's already a proper boolean, add !! for safety.

Key Takeaway: Use !! before numbers in && expressions to guarantee boolean conversion and prevent accidental rendering of 0.