JS Distinguishing Which OR Operator to Use in JSX

Codylillyw
1 min readFeb 23, 2023

?? Nullish Coalesing operator

Only returns the righhand if the left is null or undefined. This is helpful if you want to allow for a false value but not nonexistant values that could cause errors. If both are null or undefined then that will still be returned.

Use case: You are okay with false and 0 as values.

//fetch numFriends from an API
return <div>You have {numFriends ?? defaultFriends} friends.</div>

|| OR operator

Resolves to whichever is true. If the left is true it will return. Otherwise, you get the righthand. If both are false, null, or undefined the righthand will still be returned.

Use case: You want to know which is true.

return <div>You got {dndFriends || familyFriends} friends.</div>

? : Ternary

conditon: ifTrue ? ifFalse

If the lefthand is falsy the righthand will be returned.

Use case: Useful if you need to determine a value based on a third value.

return <div>You {!!hasFriends ? 'have friends' : 'have no friends'}</div>

In most cases you will likely want to use the ternary operator within JSX. Nullish and OR operator is more intended for conditional statements. I have also seen the AND(&&) operator used outside of conditionals to do something if the first statement is true since a function will always resolve to true.

true && console.log('test')

Resources

Conditional (ternary) operator — JavaScript | MDN (mozilla.org)

--

--

Codylillyw

I am a Software engineering student in my senior year with most of my experience in web development and related technology.