Nullish Coalescing in JavaScript

Nullish Coalescing in JavaScript

·

4 min read

Welcome guys! In today's blogpost, I’m going to go over Nullish Coalescing in JavaScript. Nullish Coalescing is a very hidden feature that surprisingly not a lot of developers know or have even heard about.. follow along to find out what it is, how it can be implemented, and what you can do with it!

What is Nullish Coalescing?

The Nullish coalescing ?? operator is a fairly new operator introduced to JavaScript that enables you to default to a certain value when the left-hand side is a nullish value.

A nullish value is a value that is either null or undefined.

Here’s an example:

const getName = name => {
    return name ?? "N/A";
}
console.log(getName("Velp")) // "Velp"
console.log(getName(undefined));
console.log(getName(null)); //"N/A"

Notice how when name is a nullish value (either null or undefined), then the right-hand side of the operator is executed. In this case “N/A”

This operator is useful to avoid showing undefined or null to the UI, which are often signs of bugs. Whenever possible, if you can provide a default value, you can use the nullish coalescing operator ?? to show that default value.

Some common examples include:

  • Showing an empty string "" instead of undefined or null.

  • Showing a string such as "Deleted user" instead of nullish value (undefined or null).

  • Showing "N/A" (Not Applicable) instead of a nullish value.

Short circuit

The nullish coalescing operator will short-circuit if the left-hand side returns a non-nullish value. This means that it will not execute the right-hand side. For example:

const getPlaceholder = () => {
    console.log("getPlaceholder called");
    return "N/A";
}

const sayHello = name => {
    return `Hello ${name ?? getPlaceholder()}`;
}

console.log(sayHello("Aman")); //"Hello Aman"

In this example, name is a non-nullish value so the name ?? getPlaceholder() will short-circuit meaning the getPlaceholder() function will not run. Thus, you won't see anything logged to the console.

On the other hand, if we call sayHello() (where name is undefined), then the name ?? getPlaceholder() will not short-circuit and the getPlaceholder() function will execute. Thus, you will see "getPlaceholder called" logged to the console.

Advanced

Can be used with optional chaining. The main usage is to access a property that could be nullish while also being able to default to a certain value. For Example:

let name = undefined;
if (user.details && user.details.name && user.details.name.firstName;
} else {
    name = "N/A";
}

The above code can be refactored as follows:

const name = user.details?.name?.firstName ?? "N/A"

It might be confusing to see the ?. and ?? together in the same line but remember that they are completely different operators. What happens here is that if at any point any part of this expression user.details?.name?.firstName short-circuits and returns undefined or null then we jump to the right side of the ?? operator and default to the string "N/A".

Null vs Undefined

It might be confusing why we have both null and undefined in JavaScript. So I'd like to offer some distinctions that you can think about while deciding whether to use null or undefined.

undefined means that the property has not been defined yet. Whereas, null means that the property has been defined but is empty.

In order to make the concept clearer, we're going to give you an example that illustrates the difference:

const user = {
    id: 1,
    name: "Sam",
    age: null
}

console.log(user.age); // null
console.log(user.birthday); // undefined

We used null here to mean that the age property has been defined but does not have a value yet. You can see this distinction when we try to log user.age and user.birthday. The birthday property has not been defined yet, which is why it returns undefined.

This pushed us to use the value null for age so that we can clearly tell that the age property has been defined but does not have a value yet.

If we had given the value undefined to age (which is possible), then this distinction won't hold true anymore.

Remember though, that the need to have this distinction is not very common.

const user = {
    id: 1,
    name: "Sam",
    age: null
}
console.log(user.age); //null
console.log(user.birthday);//undefined

Undefined = value that has not been discreetly defined yet

Null means the property has been defined and initialized but is empty.

Operator Precedence

The nullish coalescing operator has low operator precedence. This means that when it’s found with other operatros such as + or - and no parenthesis are used, other operators will be evaluated first. Here is another example/

const user = {
    id: 1
}
const result = 2 + user.age ?? 18;
console.log(result) //NaN

Javascript runs this as (2 + user.age) ?? 18 because + has a higher operator precedence than ??.

To avoid these issues, wrap ?? usage with parenthesis

const user = {
    id: 1
}

const result = 2 + (user.age ?? 18);
console.log(result); //20

Variable must be defined

Similar to optional chaining, you can only use nullish coalescing when the variable is defined. So, the variable name (or whatever variable you use to the left-hand side of the operator) has to be defined.

Summary

  • The nullish coalescing ?? operator is a new operator introduced in JavaScript that allows you to default to a certain value when the left-hand side is a nullish value.

  • A nullish value is a value that is either null or undefined.

  • The nullish coalescing operator will short-circuit if the left-hand side returns a non-nullish value. This means that it will not execute the right-hand side.

  • You can only use nullish coalescing when the variable is defined.

Hopefully this post helped you understand Nullish Coalescing in JavaScript better, have a great week. :-)

Did you find this article valuable?

Support Aman Velp by becoming a sponsor. Any amount is appreciated!