Demystifying the Nullish Coalescing Operator in JavaScript

Demystifying the Nullish Coalescing Operator in JavaScript

Add this tool to your js arsenal ๐Ÿ’ช

ยท

2 min read

Nullish Coalescing Operator (??) is a relatively new addition to JavaScript, introduced with ES11. In this blog, we'll explore what it is, why it's useful, and how you can leverage it in your JavaScript projects.

Syntax:

const defaultAge = age ?? 18;

In the above code snippet if age is not null or undefined defaultAge will be set to age otherwise it will be set to 18.

Before you start screaming that the logical OR (||) will do the exact same thing, hear me out.

The problem with OR (||):

const age = 23;
const defaultAge = age || 18;
console.log(defaultAge); // Output: 23

The above code will work perfectly fine in this case as it will return 18 if age is a falsy value and age otherwise. The problem occurs when we are dealing with values that could be legitimate falsy values, such as the number 0 or an empty string "".

const age = 0;
const defaultAge = age || 18;
console.log(defaultAge); // Output: 18

In this case, the default age is set to 18, even though age has a value of 0, which is a valid age. This unintended behaviour can lead to bugs and unexpected results in your code.

Nullish Coalescing Operator to the rescue ๐Ÿ›Ÿ

The Nullish Coalescing Operator (??) provides a solution to the problem mentioned above. It specifically checks for null or undefined values and doesn't treat other falsy values as null or undefined.

const age = 0;
const defaultAge = age ?? 18;
console.log(defaultAge); // Output: 0

Real-world example

export function generateMetadata({ params: { myParams } }) {
  const topic = myParams?.[0] ?? "curated";
  const page = myParams?.[1] ?? "1";

  return {
    title: `Results for ${topic} - Page ${page}`,
  };
}

The above example shows the setting of metadata using params in a next 13 server-component. The topic will show general only if we don't get data from params i.e. if it is null or undefined. Similarly for the page.

Conclusion

The Nullish coalescing operator is a great tool to resolve the issue of unintentional defaults when dealing with falsy values, ensuring that null and undefined are the only triggers for providing default values. By incorporating this operator into your code, you can write cleaner, more robust JavaScript applications with fewer surprises and bugs. So, the next time you find yourself setting default values, consider using the Nullish Coalescing Operator to make your code safer and more concise.

ย