I Don't Understand && In This JavaScript (JSX) Syntax
My understanding was that && is an 'and' operator. How can what follows && in the code block return a boolean? {accounts.length > 0 && (
Solution 1:
(if this part is true) && (this part will execute)
Solution 2:
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 totrue
, so the whole expression evaluates tofalse
. - Otherwise, it is
true
, so the whole expression evaluates toexpr2
, which in our case is aView
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.
Solution 3:
For && expression will not evaluate right side if left returns false so it's a short cut to doing following:
{accounts.length > 0 ? (
<View>
{accounts.map((account) => (
<AccountListItem
key={account.mask}
account={account}
selectedAccount={selectedAccount}
setSelectedAccount={setSelectedAccount}
/>
))}
</View>
):""}
Solution 4:
The logic operators are short circuit so if the left hand side of the expression of an and statement is false then the right hand side is not evaluated. It is a way of doing an if.
Post a Comment for "I Don't Understand && In This JavaScript (JSX) Syntax"