Simplify Your Code and Avoid Unwanted Errors with Nullish Coalescing in JavaScript

Laurentiu Raducu
3 min readFeb 20, 2023

--

Photo by Claudio Schwarz on Unsplash

JavaScript has evolved over the years with new features and updates that make it easier to write efficient and modern code. One such feature that was introduced in ECMAScript 2023 (ES2023) is Nullish Coalescing, which simplifies your code and helps you avoid unwanted errors caused by null or undefined values.

What is Nullish Coalescing?

Nullish Coalescing is a feature that allows you to provide a default value for a variable if it is null or undefined. It is an alternative to the logical OR (||) operator, which also provides a default value, but can result in unexpected behavior if the default value is a falsy value like 0 or an empty string ''.

The Nullish Coalescing operator is denoted by ?? and returns the right-hand side expression if the left-hand side expression is null or undefined, otherwise it returns the left-hand side expression.

Syntax of Nullish Coalescing

The syntax for Nullish Coalescing is simple. You use the ?? operator to provide a default value for a variable. Here's an example:

const age = 0;
const defaultAge = age ?? 18;

In this example, we use the Nullish Coalescing operator to set the defaultAge variable to 18 if age is null or undefined, otherwise it will be set to age.

Use Cases for Nullish Coalescing

Nullish Coalescing can be used in a variety of situations where you need to provide a default value for a variable if it is null or undefined. Some common use cases include:

  • Setting default values for function arguments:
function greet(name, message) {
name = name ?? 'Anonymous';
message = message ?? 'Hello';
console.log(`${message}, ${name}!`);
}

greet(); // prints "Hello, Anonymous!"

In this example, we use Nullish Coalescing to set default values for the name and message parameters of the greet function if they are null or undefined.

  • Setting default values for object properties:
const user = {
name: 'John',
age: 30
};

const city = user.city ?? 'Unknown';

In this example, we use Nullish Coalescing to set the city variable to 'Unknown' if the city property of the user object is null or undefined.

  • Checking if a value is defined:
const value = null;
const isDefined = value ?? false;

In this example, we use Nullish Coalescing to set the isDefined variable to false if the value is null or undefined.

Nullish Coalescing is a powerful feature that simplifies your code and helps you avoid unwanted errors caused by null or undefined values. It can be used in a variety of situations where you need to provide a default value for a variable, and it is now widely supported by modern browsers. If you're not already using Nullish Coalescing in your JavaScript code, it's definitely worth considering as a way to improve your code quality and reduce the risk of errors.

--

--

No responses yet