| Optional chaining | JavaScript Modules | |
π€ Nullish Coalescing Operator (??) in JavaScript |
The nullish coalescing operator (??) is a logical operator in JavaScript that returns its right-hand side operand when its left-hand side operand is null or undefined. It provides a more specific way to handle default values compared to the logical OR operator (||).
The ?? operator checks if the value on its left is "nullish," which includes only null and undefined. If it is, the operator returns the value on its right. Otherwise, it returns the value on its left. This behavior is distinct from the logical OR (||) operator, which returns the right-hand operand for any "falsy" value, including 0, an empty string (""), false, and NaN.
The ?? operator returns the right-hand operand when the left-hand operand is null or undefined. Otherwise, it returns the left-hand operand. Itβs useful for providing default values without mistakenly overriding valid falsy values like 0, false, or "".
//javascript const result = leftOperand ?? rightOperand;
This is equivalent to:
//javascript const result = (leftOperand !== null && leftOperand !== undefined) ? leftOperand : rightOperand;
// Basic usage const name = null ?? "Guest"; console.log(name); // "Guest" const age = undefined ?? 18; console.log(age); // 18 const score = 0 ?? 100; console.log(score); // 0 (not nullish, so 0 is returned) const isActive = false ?? true; console.log(isActive); // false (not nullish, so false is returned)
//javascript
const count = 0;
const text = "";
const userSettings = { volume: 0, theme: null };
// Using logical OR (||)
const qty = count || 42;
const message = text || "hello";
console.log(qty); // Output: 42 (Incorrect, as 0 is a valid count)
console.log(message); // Output: "hello" (Incorrect, as an empty string may be a valid value)
// Using nullish coalescing (??)
const qtyWithNullish = userSettings.volume ?? 42;
const messageWithNullish = text ?? "hello";
console.log(qtyWithNullish); // Output: 0 (Correct, preserves the valid falsy value)
console.log(messageWithNullish); // Output: "" (Correct, preserves the valid falsy value)
const theme = userSettings.theme ?? "light";
console.log(theme); // Output: "light" (Provides a fallback for null)
The || operator returns the right-hand operand if the left-hand operand is falsy (e.g., 0, false, "", null, undefined). In contrast, ?? only checks for null or undefined.
const value1 = 0 || 42; // 42 const value2 = 0 ?? 42; // 0
| Feature | Nullish Coalescing (??) | Logical OR (||) |
|---|---|---|
| Fallback condition | Triggers only if the left operand is null or undefined. | Triggers if the left operand is any falsy value (null, undefined, 0, "", false, NaN). |
| Preserves falsy values | Preserves valid falsy values like 0 and "". | Does not preserve falsy values; replaces them with the fallback. |
| Best for | Providing default values when you need to specifically check for truly "missing" data, but want to keep other falsy values. | Providing a fallback for any value that should be treated as "empty," including 0 or "". |
0 or false|| in many casesProviding default values for function arguments
//javascript
function greet(name, age) {
const userName = name ?? "Guest";
const userAge = age ?? "unknown";
console.log(`Hello, ${userName}! Your age is ${userAge}.`);
}
greet(null, 30); // Output: "Hello, Guest! Your age is 30."
greet("Alice", null); // Output: "Hello, Alice! Your age is unknown."
greet("Bob", 0); // Output: "Hello, Bob! Your age is 0."
Accessing potentially missing object properties
//javascript
const user = {
id: 123,
name: "Jane",
address: null
};
const userCity = user.address?.city ?? "Not specified";
console.log(userCity); // Output: "Not specified"
Handling configurations where 0 is a valid setting
//javascript
const config = { maxConnections: 0, timeout: null };
const maxConnections = config.maxConnections ?? 10;
const timeout = config.timeout ?? 5000;
console.log(maxConnections); // Output: 0
console.log(timeout); // Output: 5000
null or undefined0 or false is important|| instead)?? for nullish checks, not general falsy checksconst userName = user?.profile?.name ?? "Guest";
| Optional chaining | JavaScript Modules | |