Matt Miller
1 min readJan 26, 2020

--

If condition is false, the second operand of the && operator is not evaluated. If it is true, the second operand — or the JSX we wish to render — is returned.

It’s important to note that this can have different behavior, due to the nature of the JavaScript && operator. To quote MDN:

…the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they will return a non-Boolean value.

So, take care to not write shorthand like array.length && <ul ...> because this will print the first falsy value, 0. (The only other renderable falsy value is NaN.) Of course, this is easily fixed by writing clearer code: array.length > 0.

The one other important case is if the entire component renders conditionally, because React will throw an error if a render function returns undefined. The other falsy values null and false will work, and '' will effectively render nothing, though React will attach an unnecessary empty text node in the DOM (tested this with ReactDOM.findDOMNode() on a component that returned '').

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Matt Miller
Matt Miller

No responses yet

Write a response