π₯ 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'
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)