Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand && in this JavaScript (JSX) Syntax [duplicate]

My understanding was that && is an "and" operator. How can what follows && in the code block return a boolean?

{accounts.length > 0 && (
        <View>
          {accounts.map((account) => (
            <AccountListItem
              key={account.mask}
              account={account}
              selectedAccount={selectedAccount}
              setSelectedAccount={setSelectedAccount}
            />
          ))}
        </View>
  )}
like image 300
lifelonglearner Avatar asked Aug 06 '26 13:08

lifelonglearner


2 Answers

(if this part is true) && (this part will execute)

Conditional Rendering

like image 164
Orhan Cinar Avatar answered Aug 08 '26 02:08

Orhan Cinar


expr1 && expr2 works like this:

If expr1 can be converted to true, returns expr2; else, returns expr1.

expr1 is accounts.length > 0.

  • If this is false, then it cannot be converted to true, so the whole expression evaluates to false.
  • Otherwise, it is true, so the whole expression evaluates to expr2, which in our case is a View component.

In React, false renders nothing. You can verify this with the following minimal example:

const Test = () => <>before{false}after</>

ReactDOM.render(<Test />) // renders as "beforeafter"

In other words, in our example, if accounts.length is 0 then false is returned, rendering nothing; else, a View is returned, which is rendered.

like image 37
Lionel Rowe Avatar answered Aug 08 '26 01:08

Lionel Rowe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!