CodePark/ questions / Fundamentals & JSX
START PRACTICINGPRACTICE
Frontend question · React › Fundamentals & JSX

messages is an empty array. What does this component render?

function Inbox({ messages }) {
  return (
    <div>
      {messages.length && <p>You have {messages.length} messages</p>}
    </div>
  );
}
<div>0</div>

React renders <div>0</div>. The expression 0 && x evaluates to 0, because && returns the first falsy value. React renders numbers, so a literal 0 appears on the screen.

"An empty
<div>" is the tempting wrong answer. React skips false, null and undefined, but not 0. It does not throw either, because 0 is a valid child. To fix it, use messages.length > 0 && ... or a ternary.