JavaScript Nullish (??) Coalescing Operator

In this article, we will explore JavaScript nullish ?? coalescing or the null coalesce operator and why it matters in modern web development.

Learn how this handy feature can make your code more efficient and readable while handling null and undefined values like a pro.

Don’t miss out on this chance to improve your coding abilities. Start your journey to JavaScript mastery today with JavaScript null coalesce!

What is nullish (??) coalescing operator in JavaScript?

The JavaScript nullish coalescing operator lets you set a default value for a variable when the original value is null or undefined.

It offers a simple way to handle cases where you need to make sure a variable has a valid value and it is represented by two question marks (??).

The nullish coalescing operator ?? is a logical operator that was introduced in ECMAScript 2020 (ES11).

It returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

It is beneficial when you want to provide a default value for a variable that may be null or undefined, but not for other falsy values such as 0 or an empty string ”.

Syntax

 variable ?? defaultValue;

Examples of JavaScript null coalesce

The following are the examples that demonstrates the usage of the nullish coalescing operator in JavaScript.

Example 1:

const nullValue = null;
const empty = ""; // falsy
const number = 10;

const valX = nullValue ?? "default for X";
const valY = empty ?? "default for Y";
const valZ = number ?? 0;

console.log(valX); // output: "default for X"
console.log(valY); // output: "" (as the empty string is not null or undefined)
console.log(valZ); // output: 10

Output:

default for X

10

Example 2:

let name = null ?? "Itsourcecode";
console.log(name); // output: Itsourcecode

The return string is “Itsourcecode” because the first value is null.

Output:

Itsourcecode

Example 3:

let age = undefined ?? 18;
console.log(age); // output: 18

The output 28 because the first value is undefined.

Output:

18

Browser compatibility

Here’s the list of browsers that supports Javascript nullish coalescing:

Chrome

Edge

✅ Firefox

✅ Opera

Safari

✅ Chrome Android

✅ Firefox for Android

✅ Opera Android

✅ Safari on iOS

✅ Samsung Internet

✅ WebView Android

✅ Deno

✅ Node

How to use the nullish coalescing operator in JavaScript?

The nullish coalescing operator ?? in JavaScript can be used in various ways to handle null and undefined values.

Here are several examples to help you understand and clarify the concept of JavaScript null coalesce.

1. You can use JavaScript coalescing to provide default values for variables

Here’s an example that demonstrates how the nullish coalescing operator can be used to set a default value for a variable.

let sample1 = null;
let sample2 = sample1 ?? 'default value'; // sample2 is assigned 'default value'
console.log(`sample2: ${sample2}`); // Output: sample2: default value

In this case, if the variable sample1 is null, it will be assigned the default value ‘default value’, and then stored in the variable sample2.

Output:

sample2: default value

2. Use JavaScript null coalescing to default values for function parameters

Here’s an example that demonstrates how the nullish coalescing operator can be used to assign a default value to a function parameter.

function greet(name) {
  let greeting = name ?? 'Guest';
  console.log(`Hi, welcome to itsourcecode ${greeting}!`);
}

greet(); // Output: Hi, welcome to itsourcecode Guest!

In this case, if the name parameter is not provided when calling the greet function, the operator will set the greeting variable to ‘Guest.’

Output:

Hi, welcome to itsourcecode Guest!

3. Use JavaScript null coalesce operator to set default values for object properties

This example showcases the application of the nullish coalescing operator to set a default value for an undefined object property.

let user = {
  firstName: "It",
  lastName: "sourcecode",
  // age: 18 // property is not defined
};

let age = user.age ?? 'unknown'; // age is assigned 'unknown'

console.log(`Age: ${age}`); // Output: Age: unknown

In this example, the user object does not have an age property defined, so the nullish coalescing operator returns the right-hand side operand ‘unknown’, which is then assigned to the age variable.

The console.log statement outputs the value of age, which is ‘unknown’.

Output:

Age: unknown

4. Chaining multiple nullish coalescing operators

Here’s an example that shows how you can chain multiple nullish coalescing operators together to assign a default value when multiple variables might be null or undefined.

let a = null;
let b = undefined;
let c = 'value';

let result = a ?? b ?? c; // result is assigned 'value'

console.log(`Result: ${result}`); // Output: Result: value

In this case, both variables a and b are checked, and if either of them is null or undefined, the operator assigns the value ‘value’ to the result variable.

Output:

Result: value

What is the alternative to null coalesce in JavaScript?

Before the nullish coalescing operator ?? was introduced in JavaScript, a common way to set a default value for a variable that could be null or undefined was to use the logical OR operator ||.

Here’s an example to demonstrate this:

let a = null;
let b = a || 'default value'; // b is assigned 'default value'

console.log(`b: ${b}`); // Output: b: default value

In this example, the variable “a” is set to null. As a result, the logical OR operator returns the value on the right-hand side, ‘default value’, which is then assigned to the variable “b.” The console.log statement displays the value of “b,” which is ‘default value’.

Output:

b: default value

This example illustrates an alternative approach to the nullish coalescing operator using the logical OR operator. It allows for assigning a default value to a variable that might be null or undefined.

However, it’s important to note that the logical OR operator returns the right-hand side value if the left operand is any falsy value, not exclusively limited to null or undefined.

What is the difference between nullish coalescing (??) and the logical OR (||) operator in JavaScript?

The nullish coalescing operator (??) specifically examines null or undefined values, while the logical OR (||) operator checks for any value that evaluates to false.

Consequently, the logical OR operator treats empty strings, zero, or false as potential default values, whereas nullish coalescing solely focuses on null or undefined values.

Conclusion

In conclusion, this article explored the JavaScript nullish coalescing operator (??) and its significance in modern web development.

It is a valuable tool for handling null and undefined values in modern web development. It allows developers to set default values for variables when needed, resulting in more efficient and readable code.

The operator specifically targets null and undefined values, offering a focused alternative to the logical OR (||) operator.

Furthermore, this article shows several use cases of the nullish coalescing operator. These included setting default values for variables, assigning default values to function parameters, and setting default values for object properties.

The examples illustrated how the operator simplifies handling null and undefined values in different scenarios.

We are hoping that this article provides you with enough information that helps you understand the JavaScript nullish coalescing.

You can also check out the following article:

Thank you for reading itsourcecoders 😊.

Leave a Comment