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)