JavaScript Double Question Mark (??): What is it?

by | JavaScript

JavaScript is well-known for its robust set of features that enable developers to build dynamic web applications! One such feature is the double question mark (??), also known as the nullish coalescing operator.

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand, only when the expression on its left evaluates to null or undefined. It serves as an alternative to the logical OR (||) operator, with the key difference being its stricter evaluation of falsy values.

As a relatively new addition to the JavaScript language, it is essential for developers to understand the applications and advantages offered by the double question mark operator.

So, in this article, we’ll explain everything you need to know about this operator! Read on as we teach you how to write cleaner and more efficient code!

Let’s rock and roll!

JavaScript Double Question Mark

What is the JavaScript Double Question Mark (??) Operator?

The JavaScript double question mark (??) is an operator known as the nullish coalescing operator. Introduced in ECMAScript 2020, it offers a convenient way to handle situations where a variable or expression evaluates to null or undefined.

In JavaScript, when you want to provide a default value for a variable or expression that might be missing or not set, you typically use the logical OR (||) operator.

However, the || operator considers any Falsy value as a trigger for default substitution, not just null or undefined values.

The nullish coalescing operator (??) is more specific than the logical OR operator, as it only takes action if the left-hand expression is null or undefined.

If the left-hand expression has any other Falsy values such as false, 0, NaN, or an empty string (“”), the double question mark operator will return the left-hand expression itself.

Basic Syntax of the Nullish Coalescing Operator

To use the nullish coalescing operator, place two question marks (??) between two expressions or operands, as shown below:

leftExpression ?? rightExpression

Let’s look at a quick example of this operator at work:

const val_1 = 0
const val_2 = 'John'
const val_3 = null

console.log(val_1 ?? 'No Value')
console.log(val_2 ?? 'No Value')
console.log(val_3 ?? 'No Value')

Output:

Code output from example

As we can see in the example above, val_1 and val_2 evaluate to Falsy and Truthy respectively, so the left-hand side operand is returned.

On the other hand, val_3 is null, so the value on the right side is what is returned.

So, the second operand is returned when the first operand is either null or undefined.

What is the Difference Between the Double Question Mark (??) and OR (||) Operators?

The Nullish Coalescing Operator (??) and Logical OR (||) are both commonly used in JavaScript for handling default or fallback values. While they may appear similar at first glance, they have some key differences.

The Javascript Nullish Coalescing Operator (??) returns the right-hand-side expression only if the left-hand-side expression is either null or undefined.

On the other hand, the OR Operator (||) is a boolean logical operator that returns the right-hand-side expression if the left-hand-side expression is any Falsy value.

null, undefined, 0, false, NaN, and empty strings (“”) are all valid values for this operator.

Let’s compare both of them in this example:

const userAge = 0;
const defaultAge = 21;
const userName = undefined
const defaultName = "User_1"

console.log("OR(||) Operator")
console.log(userAge || defaultAge);
console.log(userName || defaultName);

console.log("Nullish Coalescing Operator")
console.log(userAge ?? defaultAge);
console.log(userName ?? defaultName + "\n");

Output:

Comaparison between OR and Double Question Mark

In the example above, we can see that both operators handle null and undefined values in the same way.

However, they do not handle Falsy values like 0, NaN, and empty strings similarly.

When comparing the two operators, it becomes clear that the choice between them depends on the desired behavior for falsy values.

If you only want to provide a fallback for null or undefined, the Nullish Coalescing Operator is the better choice.

However, if you require a fallback for any falsy value, the Logical OR Operator should be used.

Practical Applications of the Nulllish Coalescing Operator (??)

In this section, we will discuss some practical examples of using the double question mark (??) operator. Let’s take a look at them

Providing a Default Value for Null Variables

We can use the nullish coalescing operator to provide default values in our code. The operator will check if a variable is null or undefined and replace it with a default variable if it is.

For instance, consider the following example where we want to print out personalized greetings for guests in a hotel. If the guest’s name is null or undefined, we can use the double question mark operator to create a suitable placeholder:

const guestName = null
console.log("Hello " + guestName ?? 'Guest'+ "!" );

Output:

Hello, Guest!

In the above example, the guestName variable is null, so the greeting will show the default Guest variable.

Handling Optional Function Arguments

You can combine the double question mark operator with function parameters to set default values for your functions as well. Let’s use it to re-write the code in the previous section into a function:

function greet(name) {
  const greeting = name ?? "Guest";
  finalName = greeting[0].toUpperCase() + greeting.slice(1);
  console.log(`Hello, ${finalName}!`);
}

greet("Alice");
greet();

Output:

Code Output

In this example, a greet function takes a single parameter name. Using the double question mark operator, we can assign a default value of “Guest” if the given name is null or undefined.

The function then capitalizes the name and greets the user with it.

Now, even if we call the greet function without any arguments, we won’t run into any errors.

Handling Missing Object Properties

The double question mark operator can also be used when working with objects and their properties. When we try to call an object property that’s non-existent, what is returned is usually null or undefined.

Using the double question mark operator, we can handle this gracefully.

For example:

const user = {
  name: "John Doe",
  age: 28,
};

const name = user.name ?? "No Name";
const age = user.age ?? 25;
const address = user.address ?? "Unknown";

console.log(name);
console.log(age);
console.log(address);

Output:

John Doe
28
Unknown

In this example, we have a user object with two properties, name and age. The object does not have an address property, so the fallback value “Unknown” will be assigned.

How to Combine Double Question Mark (??) & Optional Chaining (?.)

The optional chaining operator (?.) simplifies accessing properties or calling methods from objects that might be null or undefined.

Instead of throwing an error, especially when accessing non-existent nested properties and functions, the expression short-circuits and evaluates to undefined.

For example:

const user = {
    pets : {
        cat : 'fluffy'
    }
    }

console.log(user.animal?.cat) //Without optional chaining
console.log(user.animal.cat) //With optional chaining

Output:

Optional chaining Example

In the example above, we can see that using optional chaining handles the non-existent variable graciously and returns undefined. Without it, an error occurs.

We can combine both operators to handle scenarios where a property or method might return null, undefined, or a falsy value.

Here’s an example:

const user = {
  name: null,
  age: 25,
  getAddress: function() {
    return this.address?.street ?? "Street not available";
  }
};

console.log(user.name ?? "Name not available");
console.log(user.age ?? "Age not available");
console.log(user.getAddress());

Output:

Name not available
25
Street not available

In this example, the combination of the optional chaining and nullish coalescing operators allows the code to return default values when properties are null or undefined, while still correctly handling falsy values such as 0 or false.

This interplay between the two operators helps write cleaner and safer code when dealing with objects and their properties in JavaScript.

Common Pitfalls of the Javascript Double Question Mark Operator

Short-Circuiting

One notable behavior that the bullish coalescing operator exhibits is short-circuiting. When the left operand is not null or undefined, the right-hand value is never evaluated.

This can be useful when working with expressions that may have side effects or performance impacts.

For instance:

let user = { name: "John" };
let guestCounter = 0;

let username = user.name ?? (guestCounter++, "Guest");

In this case, guestCounter will not be incremented when we run the code since the nullish coalescing operator short-circuits and does not evaluate the right-hand side.

Syntax Errors

When using the (??) operator, mixing it with the || and && operators in the same expression without using parentheses can lead to unintended behavior due to differences in operator precedence.

For example, take the following code:

let value1 = null;
let value2 = false;
let defaultValue = true;

console.log(value1 || value2 ?? defaultValue)

Output:

Syntax error

One might expect the result to be true, but it will actually result in a syntax error as shown above.

To avoid such issues, always enclose your expressions with parentheses when mixing these operators:

console.log((value1 || value2) ?? defaultValue);

Now, the result will correctly be set to true.

Final Thoughts

The JavaScript double question mark (??) operator offers a powerful and elegant solution for handling null and undefined values in your code.

Furthermore, you can leverage this robust operator to ensure that your code behaves predictably and gracefully, even in the face of unexpected data.

So, incorporate it into your projects and create more resilient and efficient JavaScript applications!

Want to learn more about Javascript? Make sure you check out our article on What is JavaScript Used For? Top 5 Applications Explained!

You can also check out this video below on the immense value ChatGPT can unlock in your Industry.

Frequently Asked Questions

Which Browsers are Compatible with the Nullish coalescing operator?

An internet browser

While modern browsers such as Google Chrome, Mozilla Firefox, Microsoft Edge, and Safari support the nullish coalescing operator out of the box, older browsers like Internet Explorer do not. Here are the primary browser versions that support the double question mark operator:

  • Google Chrome 80 and later
  • Mozilla Firefox 72 and later
  • Microsoft Edge 80 and later
  • Safari 13.1 and later
  • Opera 67 and later

Can the Double Question Mark Operator work on Object functions?

No, it cannot work on methods when used alone. It only works on Object properties. However, you can use it in conjunction with optional chaining as shown in one of the above sections to guard against missing nested methods.

Can the double question mark cause an unexpected token error?

Yes, it can. Using the double question mark operator in an environment that does not support ECMAScript 2020 or later can cause an “unexpected token error” in your JavaScript code. Always ensure that you are using a compatible environment or transpiling your code with tools like Babel to avoid such errors.

author avatar
Sam McKay, CFA
Sam is Enterprise DNA's CEO & Founder. He helps individuals and organizations develop data driven cultures and create enterprise value by delivering business intelligence training and education.

Related Posts