JavaScript's Nullish Coalescing Operator: A Beginner's Guide

JavaScript's Nullish Coalescing Operator: A Beginner's Guide

Hey geeks! Have you ever encountered a situation where you need to check if a variable is null or undefined and then assign a default value to it? If yes, then the Nullish Coalescing Operator in JavaScript can make your code simpler and cleaner.

Understanding the Nullish Coalescing Operator in JavaScript

The Nullish Coalescing Operator (??) is a new operator introduced in ES2020 that provides an easy way to check if a variable is null or undefined and then assign a default value to it.

Let's take a look at an example where we want to assign a default value to a variable if it's null or undefined:

const myVar = null ?? 'default value';
console.log(myVar); // 'default value'

In the above code, we're using the Nullish Coalescing Operator to assign a default value to the myVar variable if it's null or undefined.

Now, let's compare this with the logical OR (||) operator:

const myVar2 = null || 'default value';
console.log(myVar2); // 'default value'

At first glance, it looks like both operators are doing the same thing. However, the logical OR operator has a problem. If the variable has a falsy value other than null or undefined (e.g., '' or 0), it will also be assigned the default value:

const myVar3 = '' || 'default value';
console.log(myVar3); // 'default value'

This is where the Nullish Coalescing Operator comes in. It only assigns the default value if the variable is strictly null or undefined:

const myVar4 = '' ?? 'default value';
console.log(myVar4); // ''

In this example, myVar4 is assigned the value '' (an empty string) because it's not strictly null or undefined.

Let's take a look at another example where we have an object with nested properties and we want to check if a nested property is null or undefined:

const obj = { prop1: { prop2: 'value' } };
const nestedProp = obj.prop1.prop2 ?? 'default value';
console.log(nestedProp); // 'value'

In this example, nestedProp is assigned the value 'value' because the prop2 property is not null or undefined.

Now, let's see what happens when we set prop2 to null:

const obj2 = { prop1: { prop2: null } };
const nestedProp2 = obj2.prop1.prop2 ?? 'default value';
console.log(nestedProp2); // default value

In this case, nestedProp2 is assigned the value 'default value' because prop2 is strictly null.

So, why is the Nullish Coalescing Operator important? It simplifies your code by providing an easy way to assign default values to variables that may be null or undefined. It also ensures that only strictly null or undefined values are assigned the default value, avoiding the issue of assigning a default value to variables with falsy values.

In summary, the Nullish Coalescing Operator is a handy new operator in JavaScript that simplifies your code and avoids issues with falsy values. Give it a try in your next project!