DEV Community

loading...

Discussion on: Typescript: use the nullish coalescing operator to prevent bugs

Collapse
functional_js profile image
Functional Javascript

Good tip Maxime.

If one is using pure JavaScript, one can do:

/**
@func
if the num is nil, then return a default num instead

@param {number} def - default num to return if n is nil
@param {number} n - expected to be a num; if not, then return the default num
@return {number} - the original n or default num
*/
const getNumOrDefault = (def, n) => isNil(n) ? def : n;

usage:

//@tests
getNumOrDefault(0.5, localStorage.volume);
Collapse
ivanosevitch profile image
Ivan Poiraudeau

Thanks for the additional tip - is isNil coming from lodash?

Collapse
functional_js profile image
Forem Open with the Forem app