Why "0" is rendered on short-circuit evaluation of `array.length && ...`
That's basically the way, short-circuit evaluation is designed:
As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:
(some falsy expression) && expr is short-circuit evaluated to the falsy expression
Thus, 0 is returned with the line { list.length && <div>List rendered</div> }
.
While it is also evaluated as falsy it is not ignored on render as opposed to false
, null
, undefined
or true
.
So, if you want your short-circuit expression to return one of ignored values, you may do it this way:
{ list.length>0 && <div>List rendered</div> }
Or cast 0
to false
, like that:
{ !!list.length && <div>List rendered</div> }
Following is a quick demo as a proof of concept:
const { render } = ReactDOM
const Component = () => {
const list = []
return (
<div>
<div>Rendered on <code>{`list.length && <div>List rendered</div>`}</code>:{ list.length && <div>List rendered</div> }</div>
<div>Rendered on <code>{`list.length>0 && <div>List rendered</div>`}</code>:{ list.length>0 && <div>List rendered</div> }</div>
<div>Rendered on <code>{`!!list.length && <div>List rendered</div>`}</code>:{ !!list.length && <div>List rendered</div> }</div>
</div>
)
}
render (<Component />, document.getElementById('root'))
code {background-color: grey; color:white;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>
This isn't related to React really, but rather to JavaScript directly:
const output = list.length && "foobar";
If list.length
is falsy, then output
will take its value (so 0
in this case), and not false
as one might think.
I am a bit late to answer it but i would like to express my understandings.
As other answer by @sp00m explains clearly that it is not related to React but it is a feature of javascript.
What it does?
When the left side is falsy then it will take the value of it as in your case it will be 0
because of the [].length
. This causes to print "0"
in the DOM.
Solution:
You can make it for a truthy expectation like [].length > 0
or [].length !== 0
or !![].length
or make a ternary operator to show the component dom.
The last one converts the falsy/truthy values to a boolean value.