#Why is 0 being rendered if it is falsy value
18 messages · Page 1 of 1 (latest)
yeah but isnt 0 falsy value in js? why do I need to explicitly create boolean 🤔
for me if (x) only checks if it exists
even in PHP if (x) would be true if x is 0
because the value exists
In JS it doesn't work that way... if(0) is false in JS...
I think that your tutorial is WRONG!! OMG - so see this explanation on the React docs:
:0
Go to the section on "Inline If with Logical && Operator"
It says this:
Note that returning a falsy expression will still cause the element after && to be skipped but will return the falsy expression. In the example below, <div>0</div> will be returned by the render method.
so that's why the 0 is still rendering... that's the way React works with falsey values when doing inline operators
thank you 🙂 I spent so much time on this because it has been bothering me for the last 30 minutes, I even checked on my local env because I thought there is something wrong with scrimba
If I understood correctly that it's a React behavior, I am not sure. It is how logical && operator works in JS.
const ZERO = 0; // falsy value
console.log(ZERO && 'hi'); // 0
const ONE = 1; // truthy value
console.log(ONE && 'hi'); // 'hi'
In JS, in && "AND" conditions, the first returned value is the one which is false; if it cannot find a falsy value, it returns the last element from the conditional expression.
In || "OR" conditions, the first returned value is the one which is true; if it cannot find a truthy value, it returns the last element from the conditional expression.
Yep JJ you're right. I think that I reduced this to a React behaviour because I was thinking of this as if it were a conditional expression but it's not... it's actually more like a nullish coalescing operator:
let displayName = person.name?? 'undefined'
Where the left hand side will be returned if it's defined and the right-hand otherwise...