Member-only story

Nullish Coalescing Operator (??) — ? vs ?? — ?? vs || — Javascript

Vinodh Thangavel
1 min readJul 8, 2023

--

It is a logical operator that operate on two values and left side value is returned if not null or undefined, if not right side way returned

const tax = response.tax ?? 5

Consider response as the API response, and if tax is undefined or null , 5 will be the tax, on the other hand if we get tax from the response that will be used.

? vs ??

Don’t confuse with ? (Optional chaining) with this operator.

const tax = response?.tax ?? 5

? — Only if response object is defined, tax will be accessed to prevent errors and breaking the code (null checking)

?? — If response.tax is defined, then that will be returned, if not default value of 5

?? vs ||

|| will be a problem when operating around 0 , because 0 is considered false that value cannot be selected

even though tax amount is 0, 5 is selected, because it considers it as false, but that is not the expectation

So this operator is ideal choice when you want to have a default value when something is undefined or null

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet