Languages
[Edit]
EN

JavaScript - use throw keyword with Nullish Coalescing Operator (??) when value is null or undefined

3 points
Created by:
Creg
9600

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

  1. JavaScript - throw exception when value is null or undefined for Nullish Coalescing Operator (??)
  2. JavaScript - throw exception when value is null or undefined with Nullish Coalescing Operator (??)
  3. JavaScript - throw exception when value is null or undefined in Nullish Coalescing Operator (??)
  4. JavaScript - throw exception when value is null or undefined after Nullish Coalescing Operator (??)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join