Understanding the Difference Between „??” and „||” Operators

JavaScript icon

JavaScript

author icon

January 27, 2025

author icon

Sebastian

understanding-the-difference-between-and-operators

Javascript’s nullish coalescing operator ?? and logical OR operator || serve distinct purposes despite seeming similar. This article explores their differences and use cases.

How Work „??” (Nullish Coalescing Operator)?

The nullish coalescing operator ?? is a binary operator that returns the first operand if it’s not null or undefined, and the second operand if it’s null or undefined. It’s a shorthand way to provide a default value when working with nullable or undefined variables.

const name = null;
const fullName = name ?? 'Unknown';
console.log(fullName); // Output: Unknown

What is the Logical OR Operator (||)?

The logical OR operator || is a binary operator that returns the first truthy value it encounters. If the first operand is falsy, it returns the second operand.

const name = '';
const fullName = name || 'Unknown';
console.log(fullName); // Output: Unknown

Key Differences Between ?? and ||

While both operators can be used to provide a default value, the key differences lie in their behavior:

  • Null and undefined values (??)

    only returns the second operand if the first operand is null or undefined. In contrast, || returns the second operand if the first operand is falsy (e.g., empty string, 0, false).

  • Falsy values (||)

    treats falsy values as „false” and returns the second operand. ?? doesn’t consider falsy values as „false” and returns the first operand if it’s not null or undefined.

const name = '';
const fullName1 = name ?? 'Unknown';
console.log(fullName1); // Output: ''

const fullName2 = name || 'Unknown';
console.log(fullName2); // Output: Unknown

Use Cases for ?? and ||

  • Use ?? when working with nullable or undefined values

    is ideal when you need to provide a default value for variables that might be null or undefined.

  • Use || when working with falsy values

    is suitable when you need to provide a default value for variables that might be falsy (e.g., empty string, 0, false).

// Using ?? with nullable values
const user = { name: null, age: 25 };
const fullName = user.name ?? 'Unknown';
console.log(fullName); // Output: Unknown

// Using || with falsy values
const name = '';
const fullName = name || 'Unknown';
console.log(fullName); // Output: Unknown

Conclusion

In conclusion, while both ?? and || can be used to provide a default value, they have distinct behaviors and use cases. Understanding the differences between these two operators will help you write more concise and readable JavaScript code.