EN
JavaScript - use throw keyword with Nullish Coalescing Operator (??) when value is null or undefined
3
points
In this short article we would like to show how to use throw keyword with Nullish Coalescing Operator (??
) when value is null
or undefined
in JavaScript.
In 2024, JavaScript syntax doesn't let to use throw keyword with Coalescing Operator (??
), so it is necessary to use some tricks.
Quick solution:
const throwError = (message) => {
throw new Error(message);
};
// Usage example:
const object = ...
const item = object.item ?? throwError('Value is not available.'); // <----- the solution
Practical example
// ONLINE-RUNNER:browser;
const throwError = (message) => {
throw new Error(message);
};
// Usage example:
const object = {
a: false,
b: 0,
c: 'Text here ...',
d: null,
e: undefined
};
const a = object.a ?? throwError('`object.a` value is not available.');
const b = object.b ?? throwError('`object.b` value is not available.');
const c = object.c ?? throwError('`object.c` value is not available.');
const d = object.d ?? throwError('`object.d` value is not available.'); // it throws exception
const e = object.e ?? throwError('`object.e` value is not available.'); // it throws exception
Alternative titles
- JavaScript - throw exception when value is null or undefined for Nullish Coalescing Operator (??)
- JavaScript - throw exception when value is null or undefined with Nullish Coalescing Operator (??)
- JavaScript - throw exception when value is null or undefined in Nullish Coalescing Operator (??)
- JavaScript - throw exception when value is null or undefined after Nullish Coalescing Operator (??)