What does the ?? (nullish coalescing) operator do in JavaScript?

The `??` operator, known as the "nullish coalescing" operator, is a logical operator introduced in ECMAScript 2020 (ES11) to provide a concise way to handle default values when dealing with potentially `null` or `undefined` values.

The nullish coalescing operator returns the right-hand operand when the left-hand operand is `null` or `undefined`; otherwise, it returns the left-hand operand. It specifically checks for `null` or `undefined` and does not consider other falsy values.

Here's a simple example:

let variable1 = null;
let variable2 = "Hello, world!";

let result = variable1 ?? variable2;

console.log(result);  // Outputs: "Hello, world!"


In this example, `result` is assigned the value of `variable2` because `variable1` is `null`. If `variable1` were any falsy value other than `null` or `undefined` (like `0` or an empty string), the `??` operator would still choose `variable1`.

Comparison with the `||` (logical OR) operator:

let variable1 = null;
let variable2 = "Hello, world!";

let result = variable1 || variable2;

console.log(result);  // Outputs: "Hello, world!"


While the `||` operator would also choose `variable2` in this case, it would do so for any falsy value on the left side (not just `null` or `undefined`). This subtle difference makes the nullish coalescing operator more precise when dealing specifically with the absence of a value.

The nullish coalescing operator is especially useful when setting default values for variables or function parameters, ensuring that only `null` or `undefined` triggers the fallback value.