Double Question Mark ?? in JavaScript, TypeScript and React

JavaScript ??

In JavaScript, the double question mark ?? is called “nullish coalescing operator.” It is a relatively new addition to the language, introduced in ECMAScript 2020 (ES11). nullish coalescing operator provides a concise way to handle default values when dealing with null or undefined values.

The syntax of nullish coalescing operator is as follows:

const result = valueToCheck ?? defaultValue;

valueToCheck: This is the variable or expression whose value you want to check for null or undefined.

defaultValue: This is the value that will be assigned to result if valueToCheck is either null or undefined.

nullish coalescing operator differs from the logical OR (||) operator in one important aspect. The || operator performs a “truthy” check, which means it returns the right-hand operand if the left-hand operand is falsy (e.g., false, 0, “”, null, undefined, NaN). In contrast, the ?? operator performs a “nullish” check, which returns the right-hand operand only when the left-hand operand is null or undefined.

Let’s see an example to illustrate this difference:

const foo = 0;
const bar = null;
const baz = '';
console.log(foo || 'default'); // Output: 'default' (0 is falsy)
console.log(bar || 'default'); // Output: 'default' (null is falsy)
console.log(baz || 'default'); // Output: 'default' (empty string is falsy)
console.log(foo ?? 'default'); // Output: 0 (0 is not null or undefined)
console.log(bar ?? 'default'); // Output: 'default' (null is nullish)
console.log(baz ?? 'default'); // Output: '' (empty string is not null or undefined)

In the example above, you can observe that nullish coalescing operator returns the default value only when the left-hand operand is null or undefined, while the logical OR operator returns the default value for all falsy values. This makes ?? particularly useful when you want to handle only null or undefined cases and avoid unintentionally using a default value for other falsy values.

Typescript ??

In TypeScript, nullish coalescing operator ?? works similarly to JavaScript. It was introduced as part of TypeScript 3.7, which aligns with ECMAScript 2020 (ES11). The purpose and behavior of the operator are the same as in JavaScript.

nullish coalescing operator is especially useful in TypeScript when you want to handle default values for nullable types, such as when dealing with optional properties, function arguments, or nullable variables. Get started with typescript

function greet(name?: string): string {
  const defaultName = 'Guest';
  const finalName = name ?? defaultName;
  return `Hello, ${finalName}!`;
}
console.log(greet());          // Output: "Hello, Guest!"
console.log(greet(undefined)); // Output: "Hello, Guest!"
console.log(greet(null));      // Output: "Hello, Guest!"
console.log(greet("Sam"));    // Output: "Hello, Sam!"

In this example, the greet function takes an optional parameter name, which represents a nullable string. If name is not provided, undefined, or null, nullish coalescing operator ?? assigns the default value 'Guest' to finalName. If name has a valid value, that value is used as finalName.

The TypeScript compiler understands nullish coalescing operator and provides proper type inference based on the usage of ??. For instance, in the example above, the finalName variable is inferred to be of type string because both name and defaultName are of type string. If name was of type string | null | undefined, finalName would also be inferred as string | null | undefined due to the usage of ??.

TypeScript provides additional safety by performing static type checking, and the use of nullish coalescing operator can help ensure that you handle null and undefined cases more explicitly in your code.

React ??

In React, nullish coalescing operator ?? works just like in JavaScript and TypeScript. React, being built on JavaScript, supports all the language features, including nullish coalescing operator.

In React applications, you can use the ?? operator to handle default values for props or state variables that might be nullable (i.e., null or undefined). It helps provide a concise and safe way to handle cases where a value might be missing, allowing you to specify fallback values when needed.

using nullish coalescing operator in a React component:

import React from 'react';
const Greeting = ({ name }) => {
  const defaultName = 'Guest';
  const finalName = name ?? defaultName;
  return <div>Hello, {finalName}!</div>;
};
export default Greeting;

In this example, the Greeting component receives a name prop. nullish coalescing operator is used to set a default value of 'Guest' for finalName if the name prop is null or undefined.

Usage of this component:

import React from 'react';
import Greeting from './Greeting';
const App = () => {
  return (
    <div>
      <Greeting name="Sam" />       // Output: Hello, Sam!
      <Greeting name={null} />       // Output: Hello, Guest!
      <Greeting name={undefined} />  // Output: Hello, Guest!
    </div>
  );
};
export default App;

As seen in the App component, when Greeting is used with different name prop values (including null and undefined), nullish coalescing operator ensures that the default value 'Guest' is used when name is not provided or is nullable.

nullish coalescing operator is a handy tool in React development for managing default values and providing more robust handling of nullable props and state variables.

Don't Miss Out! Subscribe to Read Our Latest Blogs.

If you found this blog helpful, share it on social media.

Subscription form (#5)

Pin It on Pinterest

Scroll to Top