DEV Community

Dzung Nguyen
Dzung Nguyen

Posted on

🌟 Nullish Coalescing Operator (??) vs OR (||) in JavaScript : When to Use Each?

🔥 In JavaScript, the Nullish Coalescing Operator (??) provides a way to handle null and undefined values more effectively.

Comparisons

👉 The nullish coalescing operator (??) returns the right-hand value only if the left-hand value is null or undefined. It does not treat other falsy values (0, false, NaN, "") as nullish.

👉 The logical OR (||) operator returns the right-hand side value if the left-hand side is falsy (0, false, "", null, undefined)

Examples

// ✅ Example 1: Basic usage
const value1 = null ?? 'Default Value';
console.log(value1); // Output: 'Default Value'

const value2 = undefined ?? 'Fallback';
console.log(value2); // Output: 'Fallback'


// ✅ Example 2: Difference between ?? and ||
const zero = 0 ?? 100;
console.log(zero); // Output: 0 (because 0 is not null or undefined)

const zeroOr = 0 || 100;
console.log(zeroOr); // Output: 100 (because 0 is falsy)


// ✅ Example 3: Chaining with multiple values
const result = null ?? undefined ?? '' ?? 'First non-null value';
console.log(result); // Output: ''


// ✅ Example 4: With function parameters
function greet(name) {
    const displayName = name ?? 'Guest';
    console.log(`Hello, ${displayName}!`);
}
greet();        // Output: Hello, Guest!
greet('Alice'); // Output: Hello, Alice!


// ✅ Example 5: Nested objects with optional chaining
const user = {
    profile: {
        age: null
    }
};
const age = user?.profile?.age ?? 'Unknown';
console.log(age); // Output: 'Unknown'
Enter fullscreen mode Exit fullscreen mode

Documentation

💎 Nullish Coalescing Operator: https://lnkd.in/gvrzu53T
💎 Logical OR: https://lnkd.in/gy3xqtX6

Happy coding! 🚀


Follow me to stay updated with my future posts:

Top comments (0)