Flexiple Logo
  1. Home
  2. Blogs
  3. JavaScript
  4. The Double Question Mark (??) in JavaScript

The Double Question Mark (??) in JavaScript

Author image

Harsh Pandey

Software Developer

Published on Tue Apr 23 2024

The double question mark in JavaScript, known as the nullish coalescing operator, provides a robust method for assigning default values. It evaluates its left-hand operand and, if the value is null or undefined, returns the right-hand operand; otherwise, it returns the left-hand value. This operator ensures that JavaScript developers can handle potentially empty variables more predictably and concisely. It is particularly useful in scenarios where default settings need to be established without falsely capturing zero or empty strings as null values.

What is the ?? Operator?

The ?? operator in JavaScript is known as the nullish coalescing operator. It returns the right-hand operand when the left-hand operand is either null or undefined. This operator provides a reliable way to specify default values. It does not trigger for falsy values like 0 or an empty string, distinguishing it from the logical OR operator. Thus, it ensures that only null or undefined values are replaced with a specified default.

How Does the Double Question Mark Work?

The double question mark in JavaScript, known as the nullish coalescing operator, operates by returning the right-hand operand when the left-hand operand is either null or undefined. If the left-hand operand has a value other than null or undefined, it returns that value instead.

Here's a simple usage example:

let userColor = null;

let defaultColor = "blue";

let currentColor = userColor ?? defaultColor;

// currentColor will be "blue"

This operator is particularly useful for setting default values. It ensures that only values explicitly set to null or undefined trigger the use of a fallback value. This behavior distinguishes it from the logical OR operator (||), which returns the right-hand operand for any falsy left-hand operand, including 0, "", or false.

Use Cases for ??

  1. Setting Defaults: The most common use of the nullish coalescing operator is to provide a default value for potentially null or undefined variables without accidentally catching other falsy values that might be valid (like 0 or false).
  2. Configuration Settings: Useful in application configuration tasks where parameters may be omitted but should default to a specific value.
  3. Prop Handling in Components: In frameworks like React, ?? can provide default values for props that haven’t been passed from the parent component.

Differences Between ?? and ||

The differences between the double question mark (??) and the logical OR (||) in JavaScript are important for handling values in different scenarios.

The double question mark, known as the nullish coalescing operator, specifically checks for null or undefined. If the left-hand operand is either null or undefined, it returns the right-hand operand. For example:

let result = null ?? "default value";

console.log(result); // Outputs: "default value"

In contrast, the logical OR operator (||) checks for any falsy value, which includes 0, "" (empty string), NaN, false, null, and undefined. It returns the right-hand operand if the left-hand is falsy. This can lead to unexpected results when handling values that are falsy but valid in a given context. Consider:

let count = 0;

let total = count || 10;

console.log(total); // Outputs: 10

In summary, use ?? when you need to handle null or undefined without interfering with other falsy values. Use || when any falsy value should trigger the use of a default.

Combining ?? With Other Operators

Combining the double question mark (??) with other operators in JavaScript can enhance nullish value handling in expressions. The ?? operator is specifically used to return the right-hand operand when the left-hand operand is either null or undefined. It's crucial for ensuring that variables have a default value.

One common scenario involves combining ?? with the logical AND (&&) or logical OR (||) operators. Here's how it works:

let defaultName = user.name ?? "Anonymous";

let message = (user.greet || "Hello") + ", " + defaultName;

In the example above, defaultName uses ?? to provide a fallback if user.name is nullish. The message then concatenates a greeting, using || to provide a default greeting if user.greet is falsy, not just nullish.

It is important to understand operator precedence when combining ?? with other operators. Specifically, ?? cannot be directly mixed with || or && without using parentheses due to potential ambiguity in interpretation. Here's a corrected approach:

let isActive = (user.status ?? "offline") === "online";

In this corrected code, parentheses ensure the ?? operation resolves before comparing the result with "online". This maintains clear logic flow and prevents errors. Always prioritize clarity and safety in expressions involving multiple operators.

Browser and Environment Compatibility

The double question mark, or nullish coalescing operator (??), in JavaScript is widely supported in modern browsers and environments. This operator allows developers to provide a default value when dealing with null or undefined inputs.

Major browsers like Chrome, Firefox, Safari, and Edge fully support the ?? operator. The compatibility extends to their respective mobile versions as well, ensuring a broad coverage across devices.

In terms of JavaScript environments, Node.js supports this operator from version 14 onwards. It is also available in Deno from its initial releases.

For older browsers or environments that do not recognize the ?? operator, a Babel plugin can be used to transpile code to be ES5-compatible. This ensures that applications using nullish coalescing still function in legacy systems.

Detailed Usage and Examples

Here are some practical examples showing how to use the nullish coalescing operator:

Example 1: Basic Usage

const foo = null ?? 'default string';

console.log(foo);

// Output: "default string"

Example 2: Combining with Optional Chaining

const baz = { bar: { baz: 3 }};

const value = baz?.bar?.baz ?? 42;

console.log(value);

// Output: 3

Example 3: Complex Chaining

const settings = { theme: null };

const theme = settings.theme ?? 'dark';

console.log(theme);

// Output: "dark"

Interaction with Optional Chaining

Optional chaining (?.) and nullish coalescing (??) are often used together. Optional chaining provides a way to navigate deeply nested object properties without causing errors if a reference is nullish:

const nestedValue = obj?.prop?.mightBeUndefined ?? 'default value';

Polyfills and Transpilation

To support older browsers, a polyfill or transpilation step is required. Babel, for instance, offers plugins that transform ?? into a format that older JavaScript engines can execute. Similarly, TypeScript provides down-compilation options that handle ?? correctly.

Conclusion

The introduction of the nullish coalescing operator in JavaScript is a significant improvement for handling null and undefined values cleanly and explicitly. By providing a mechanism to deal with absence of data without the false positives of the logical OR operator, ?? allows developers to write safer, more predictable code especially in conjunction with optional chaining. Whether for setting default values, configuring applications, or handling optional object properties, the ?? operator is a powerful addition to JavaScript's expression syntax.

Related Blogs

Browse Flexiple's talent pool

Explore our network of top tech talent. Find the perfect match for your dream team.