solidjs / solid

A declarative, efficient, and flexible JavaScript library for building user interfaces.
https://solidjs.com
MIT License
32.47k stars 927 forks source link

Unexpected values in For loop when nullish coalescing operator used with additonal ternary check #2215

Closed martinpengellyphillips closed 4 months ago

martinpengellyphillips commented 4 months ago

Describe the bug

When a nullish coalescing operator is used with an additional ternary check within a <For> loop, Solid appears to render a duplicate and incorrect value for every item.

Your Example Website or App

https://playground.solidjs.com/anonymous/8888fdd6-3c51-43ad-a7c8-18f26f57574c

Steps to Reproduce the Bug or Issue

  1. Use the toggle button in the shared reproducible test case to see the effect.
  2. Note that when nullish coalescing operator used with additional ternary, the output is incorrect.

Expected behavior

List should output the same with nullish coalescing operator as with using multiple ternary operators.

Screenshots or Videos

Kapture 2024-07-07 at 20 37 42

Platform

Additional context

No response

maciek50322 commented 4 months ago

I think it has to do with order of operations, the ?? is higher than ? ... : ..., and so the line

return <>{meta.highlight ?? item.id === 2 ? 'PEAR' : item.name}</>;

is same as

return <>{(meta.highlight ?? item.id === 2) ? 'PEAR' : item.name}</>;

and because meta.highlight is always truthy, it immediately jumps to 'PEAR'

to fix this, try using parenthesis different way

return <>{meta.highlight ?? (item.id === 2 ? 'PEAR' : item.name)}</>;
martinpengellyphillips commented 4 months ago

Indeed! Thanks for the hint. Closing this as user error :)