How to set a default value
Short answer
The ?? operator returns the right value only if the left one is null or undefined:
const limit = undefined;
console.log(limit ?? 10);Output:
10Function parameters
A default value can be written right in the parameter list:
const greet = (name = 'guest') => `Hello, ${name}!`;
console.log(greet());
console.log(greet('Anna'));Output:
Hello, guest!
Hello, Anna!In destructuring
When unpacking an options object, set defaults for each field:
const createButton = ({ text = 'OK', color = 'blue' } = {}) => `${text} (${color})`;
console.log(createButton({ text: 'Save' }));
console.log(createButton());Output:
Save (blue)
OK (blue)Assigning only if empty
??= writes a value only if the property is empty:
const options = { retries: 0 };
options.retries ??= 3;
options.timeout ??= 5000;
console.log(options.retries, options.timeout);Output:
0 5000Common mistake
The || operator replaces all falsy values, including 0 and an empty string:
const volume = 0;
console.log(volume || 50);
console.log(volume ?? 50);Output:
50
0Functions used in this recipe
- Nullish coalescing (??) — Returns the right-hand value if the left is null or undefined.
- Destructuring assignment — Unpacks values from an array or object into separate variables.