Understanding Double Question Mark Operator (??) in TypeScript
Published: 2023-07-03 13:17:24

The double question mark operator, also known as the nullish coalescing operator, is a feature introduced in TypeScript to provide a concise way to handle null or undefined values. It is represented by ??.

When used, the double question mark operator checks if the value on the left-hand side is null or undefined. If it is, the operator returns the value on the right-hand side. However, if the value on the left-hand side is not null or undefined, it is returned as is.

This operator differs from the logical OR operator (||) in that it only returns the right-hand side value if the left-hand side value is null or undefined, rather than any falsy value.

Here's an example usage of the double question mark operator:

```typescript
const defaultValue = "Default Value";
const value = null;
const result = value ?? defaultValue;

console.log(result); // Output: "Default Value"
```

In the above code, value is null, so the double question mark operator returns the defaultValue instead.

## Syntax of the double question mark operator
The double question mark operator, also known as the nullish coalescing operator, is a feature introduced in TypeScript. It provides a concise way to handle null or undefined values in expressions.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7vlkv5o20tjcdmx675zy.png)


The syntax for using the double question mark operator is value1 ?? value2, where value1 is the expression to be evaluated and value2 is the fallback value to be used if value1 is null or undefined. This operator helps to simplify conditional checks and provides a more streamlined approach to handling nullish values in TypeScript code.

In TypeScript, the double question mark operator (??) can be used to assign a default value to a variable if it is null or undefined. This is useful when working with optional values or handling potential null values.

Here's an example:

```
let name: string | null = null;
let displayName: string = name ?? "Guest";

console.log(displayName); // Output: "Guest"
```

In the above code snippet, the name variable is assigned a value of null. When we use the double question mark operator (??) to assign a default value to displayName, it checks if name is null or undefined. Since name is null, the default value "Guest" is assigned to displayName.

This allows us to provide a fallback value in case the variable is not defined or has a null value.

## Difference between nullish coalescing and logical OR operator
In TypeScript, the nullish coalescing operator (??) and the logical OR operator (||) are used for different purposes.

The nullish coalescing operator is used to provide a default value when the operand on the left-hand side is null or undefined. It works by returning the right-hand side value if the left-hand side value is null or undefined, otherwise it returns the left-hand side value.

On the other hand, the logical OR operator is used to determine the truthiness of the values on both sides. It returns the first truthy value between the two operands. However, if both operands are falsy, it returns the right-hand side value.

Therefore, while the nullish coalescing operator is specifically designed to handle null and undefined values, the logical OR operator does not make this distinction and can be used with any values.

Here's an example:

```typescript
const name = null;
const defaultName = "John Doe";

const displayName = name ?? defaultName;

console.log(displayName); // Output: "John Doe"
```

In this example, the variable name is assigned a value of null. The nullish coalescing operator (??) is then used to assign the value of name to displayName. However, since name is null, the operator falls back to the default value of defaultName, which is "John Doe". As a result, the value of displayName is "John Doe".

The double question mark operator provides a convenient way to handle null or undefined values and ensures that a default value is returned when needed.

## Handling Undefined and Null Values
The double question mark operator (??) in TypeScript handles undefined and null values differently. When using this operator, if the value on the left-hand side is null or undefined, it will be replaced by the value on the right-hand side.

However, if the value on the left-hand side is any other falsy value (such as an empty string or 0), it will not be replaced and will be returned as is. This behavior allows for concise and reliable handling of potentially undefined or null values in TypeScript code.

```typescript
const name: string | undefined = undefined;
const defaultName: string = "John Doe";

const displayName: string = name ?? defaultName;

console.log(displayName); // Output: "John Doe"
```

In the above example, the variable name is undefined. By using the double question mark operator (??), we assign the value of defaultName to displayName. This ensures that displayName has a fallback value when name is undefined.

## Chaining the Double Question Mark Operator in TypeScript
The double question mark operator (??) in TypeScript allows for chaining multiple expressions in a concise and efficient manner. When used in a chain, each expression is evaluated in order until a non-null or non-undefined value is found.

If all expressions in the chain are null or undefined, the operator returns the final expression. This chaining behavior helps to simplify nullish coalescing operations by providing a clean and readable syntax. It enables developers to handle default values or fallback scenarios easily without the need for lengthy if-else statements.

Here's an example to illustrate this functionality:

```typescript
const firstName = null;
const lastName = undefined;
const fullName = firstName ?? lastName ?? 'John Doe';

console.log(fullName); // Output: "John Doe"
```

In the above code snippet, we have two variables firstName and lastName with values of null and undefined, respectively. We then use the double question mark operator to provide a default value of 'John Doe' if both firstName and lastName are null or undefined. The resulting value of fullName is "John Doe".

## Type Safety with Double Question Mark Operator
When using the double question mark operator (??), TypeScript performs type inference to determine the resulting type. This means that if the left-hand side of the operator is of a union type, TypeScript will infer the resulting type based on the common types of the operands.

Type safety is also maintained when using the double question mark operator. TypeScript ensures that the resulting value of the expression is of the same type as the left-hand side operand. This helps prevent potential type errors and allows developers to write more robust and reliable code.

In situations where nullish values need to be handled, the double question mark operator offers a concise and type-safe solution in TypeScript.

Let's consider a few examples to understand how it can be used with different types and how it helps in dealing with type errors.

### Using the operator with strings:

```typescript
const name: string | undefined = undefined;
const defaultName: string = "John Doe";
const result: string = name ?? defaultName;
console.log(result); // Output: "John Doe"
```

In this example, the operator checks if the name variable is null or undefined. If it is, the defaultName value is used instead. This prevents potential runtime errors caused by accessing properties or methods on a null or undefined value.

### Using the operator with numbers:

```typescript
const quantity: number | null = null;
const defaultQuantity: number = 0;
const result: number = quantity ?? defaultQuantity;
sole.log(result); // Output: 0
```

Here, the operator checks if the quantity variable is null or undefined. If it is, the defaultQuantity value is used. This ensures that calculations or comparisons involving numbers are handled correctly, even if the original value is missing.

### Handling type errors:

```typescript
const age: number | null = null;
const result: number = age ?? "N/A";
console.log(result); // Output: Error - Type 'string' is not assignable to type 'number'
```

In this case, the operator encounters a type error because the age variable is of type number | null, but the fallback value is of type string. TypeScript's type checking helps identify such errors at compile-time, ensuring type safety and preventing potential issues during runtime.

By using the double question mark operator, we can write more robust and error-free code, handling potential null or undefined values effectively and gracefully.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nnbv4die4xv5qcnvkxyy.png)


## Limitations and Edge Cases When Using the Double Question Mark Operator
When utilizing the double question mark operator in TypeScript, there are a few limitations and edge cases to be aware of.

Firstly, the double question mark operator can only be used with nullable types. It cannot be applied to non-nullable types, such as number or boolean. Attempting to use the operator on a non-nullable type will result in a compilation error.

Additionally, the double question mark operator only checks for null or undefined values. It does not handle other falsy values like 0, empty strings, or false. Therefore, if you need to handle these values as well, alternative approaches must be considered.

Furthermore, the double question mark operator does not provide type narrowing or inference. This means that the resulting value will still retain its original type, even if the check is successful.

Lastly, it is important to note that the double question mark operator can only be used with TypeScript version 3.7 or higher. If you are using an older version, this operator will not be available.

## Precautions to take when using the operator to avoid unexpected behavior
When using the double question mark operator (??) in TypeScript, there are a few precautions to keep in mind to avoid unexpected behavior.

1. Type compatibility: Ensure that the types on both sides of the operator are compatible. If the types do not match, it may lead to unexpected results or errors.
2. Order of evaluation: Be aware of the order in which the expressions are evaluated. The double question mark operator evaluates the expression on the left first, and only if it is null or undefined, it returns the value on the right. Make sure this order aligns with your intended logic.
3. Avoid nested operators: Nesting multiple double question mark operators can make the code harder to read and understand. It is advisable to use alternative approaches, like conditional statements or functions, for complex scenarios.
4. Side effects: Take into consideration any potential side effects that the operator may have. For example, if the expression on the left has a side effect, it will still be executed even if the value is ultimately discarded by the operator.

By being mindful of these precautions, you can safely utilize the double question mark operator in TypeScript and minimize unexpected behavior in your code.

## Learn TypeScript Programming with [TypeScript Online Compiler](https://www.lightly-dev.com/typescript/)
Are you struggling with solving errors and debugging while coding? Don't worry, it's far easier than climbing Mount Everest to code. With Lightly IDE, you'll feel like a coding pro in no time. With [Lightly IDE](https://www.lightly-dev.com/), you don't need to be a coding wizard to program smoothly.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1sa6nbshd7wm2yjnsvy7.png)

One of its notable attributes is its artificial intelligence (AI) integration, enabling effortless usage for individuals with limited technological proficiency. By simply clicking a few times, one can transform into a programming expert using Lightly IDE. It's akin to sorcery, albeit with less wands and more lines of code.

For those interested in programming or seeking for expertise, Lightly IDE offers an ideal starting point with its TypeScript online compiler. It resembles a playground for budding programming prodigies! This platform has the ability to transform a novice into a coding expert in a short period of time.

Read more: [Understanding Double Question Mark Operator (??) in TypeScript](https://www.lightly-dev.com/blog/typescript-double-question-mark/)