THAPA TECHNICAL

HOUSE OF WEB DEVELOPERS AND TECHNOLOGY.

Difference between || and ?? operators in JavaScript

How to use the logical OR operator (||) and the nullish coalescing operator (??) in JavaScript:

const userName = req.body.name || 'Anonymous'; // Using || const userAge = req.body.age ?? 25; // Using ??

In the first line, the userName variable will be set to the value of req.body.name if it exists and is not null or undefined. If req.body.name is null or undefined, then userName will be set to the default value of 'Anonymous'.


In the second line, the userAge variable will be set to the value of req.body.age if it exists and is not null or undefined. If req.body.age is null or undefined, then userAge will be set to the default value of 25.


It's worth noting that the logical OR operator (||) has different behavior when dealing with falsy values. In JavaScript, the following values are considered falsy: false, 0, '' (an empty string), null, undefined, and NaN. If the value on the left side of the || operator is falsy, then the value on the right side will be returned, regardless of whether it is null or undefined.


For example:

const userName = '' || 'Anonymous'; // 'Anonymous' const userAge = 0 || 25; // 25

In these examples, the userName variable will be set to 'Anonymous' because the left-side value of '' is considered falsy, and the userAge variable will be set to 25 for the same reason.


On the other hand, the nullish coalescing operator (??) will only return the right-side value if the left-side value is strictly null or undefined. It will not return the right-side value for any other falsy values.


For example:

const userName = '' ?? 'Anonymous'; // '' const userAge = 0 ?? 25; // 0

In these examples, the userName variable will be set to the left-side value of '' because it is not strictly null or undefined, and the userAge variable will be set to the left-side value of 0 for the same reason.