0

Given value = NaN When value && value > 0 && <Component>.

For some reason, the app renders "NaN" rather than not rendering anything. Am I missing something? I would have thought that because NaN is not greater than 0...it would not render anything?

4
  • did you check if value > 0 returns true if value = NaN? Since it seems your if statement returns true if it renders NaN Commented Jun 23, 2020 at 15:41
  • NaN is considered truthy so when NaN > 0 fails the chained && will just "return" the last truthy part of it. Commented Jun 23, 2020 at 15:42
  • 1
    @apokryfos where did you find that NaN is truthy? here states the opposite: developer.mozilla.org/en-US/docs/Glossary/Falsy Commented Jun 23, 2020 at 15:44
  • @MarioVernari No you're right I misspoke. The failed && will return the value it failed with. That seems to be in that link as well Commented Jun 23, 2020 at 15:45

2 Answers 2

3

The logical AND (&&) expression syntax is:

expr1 && expr2

According to the documentation:

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

Because NaN is expr1 and is falsy, NaN is returned.

If you want the component to render only if value exists and is a number greater than 0, you may be able to simply write:

value > 0 && <Component>
Sign up to request clarification or add additional context in comments.

1 Comment

Sidenote: The react docs seem to say that only null and false values do not produce any rendered output. I guess undefined might work as well but other falsy values are rendered
0

so you basically might give this a shot

if value !== NaN {
    if value && value > 0 && <Component> {
       // do something 
    } else {}
} else {}

or chain the entire logic, but personally I'd prefer this for readability

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.