In JavaScript, the ?? operator is known as the nullish coalescing operator . It is used to provide a default value when the left-hand side operand is null or undefined. This operator is useful for handling cases where a variable may be null or undefined and you want to assign a fallback value.
Syntax:
let result = a ?? b;
a is the value to be checked.
b is the fallback value if a is null or undefined.
Example:
let foo = null;
let bar = foo ?? 'default value';
console.log(bar); // Output: 'default value'
let baz = 0;
let qux = baz ?? 'default value';
console.log(qux); // Output: 0
How it Works:
If foo is null or undefined, bar will be assigned the value 'default value'.
If foo has any other value (including 0, false, or an empty string), bar will be assigned the value of foo.
Difference from || (Logical OR) Operator
The logical OR operator (||) also provides a way to fall back to a default value, but it treats other falsy values (0, false, NaN, '', etc.) as false and will use the right-hand side value in those cases.
If you want to read more:
https://www.freecodecamp.org/news/what-is-the-nullish-coalescing-operator-in-javascript-and-how-is-it-useful/