Skip to content
Dev Discovers

Understanding the ?? operator in JavaScript

javascript2 min read

JavaScript has a number of operators that can be used to perform various operations. One of these operators is the nullish coalescing operator, also known as the ?? operator. This operator is used to check if a value is null or undefined and provide a default value in case it is. In this article, we'll explore the ?? operator and its usage in JavaScript.

How does the ?? operator work?

The ?? operator checks if a value is null or undefined and provides a default value if it is. It works like this:

const result = value ?? defaultValue;

Here, value is the variable that we want to check for null or undefined, and defaultValue is the value that we want to use as the default in case value is null or undefined.

If value is not null or undefined, the operator returns the value of value. If value is null or undefined, the operator returns the value of defaultValue.

Examples of using the ?? operator

Here are some examples of how you can use the ?? operator in your JavaScript code:

const name = null;
const defaultName = 'John Doe';
// Using the ?? operator
const result = name ?? defaultName;
console.log(result); // Output: "John Doe"

In this example, the name variable is set to null. We then use the ?? operator to check if name is null or undefined. Since it is, the operator returns the value of defaultName, which is "John Doe".

Here's another example:

const age = 0;
const defaultAge = 18;
// Using the ?? operator
const result = age ?? defaultAge;
console.log(result); // Output: 0

In this example, the age variable is set to 0. However, 0 is not null or undefined, so the operator returns the value of age, which is 0.

If you're interested in learning more about the ?? operator, you can check out the MDN documentation. The documentation provides additional examples and detailed information on the operator's behavior.

Final Thoughts

The nullish coalescing operator, or ?? operator, is a useful tool in JavaScript that can be used to provide default values for null or undefined variables. By using the ?? operator, you can write more concise and readable code, and avoid unexpected errors that can occur when working with null or undefined values.

© 2023 by Dev Discovers. All rights reserved.
Theme by LekoArts