Skip to main content

orElse()

orElse<T>(fn, fallback): T

Executes a function and returns its result, or a fallback value if an error occurs.


Type Parameters​

T: T​

The return type.


Parameters​

fn: () => T​

The function to execute.

fallback: T​

The value to return if the function throws an error.


Returns: T​

The result of the function or the fallback value.


Since​

2.0.0


Example​

const result = orElse(() => JSON.parse('invalid json'), {});
console.log(result); // {}

const value = orElse(() => localStorage.getItem('key'), 'default');
console.log(value); // 'default' if localStorage throws or key doesn't exist

const number = orElse(() => parseInt('abc'), 0);
console.log(number); // 0