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

Popular posts from this blog

angularjs ui-router query string parameter support

typescript notes (typeof, keyof, ReturnType, Parameters, Extract)

react-select stacking order bug, z-index, layers and stacking