nullish coalescing versus logical or
Is this code ok?
customer?.type || ''
Probably, but strictly semantically speaking this should use '??' (nullish coalescing) instead of '||'
The left side condition uses optional chaining which resolves to a value or undefined, ?? is more strict and only fires for null or undefined. Whereas '||' will execute for more values than null or undefined (also 0, false, NaN, '')
So if customer.type was 0 then using '||' will resolve to the right side
customer?.type || 'none' // 'none'
whereas if customer.type was 0 then using '||' will resolve to the left side
customer?.type || 'none' // 0
Comments
Post a Comment