To set a default value only in case of a nullish value (i.e. undefined
or null
), you can do the following:
- Use the Nullish Coalescing Operator;
- Use the Nullish Assignment Operator;
- Explicitly Check for Nullish Value.
Using the Nullish Coalescing Operator
If the left-hand side of an expression is nullish value, then you can simply use the nullish coalescing operator (??
) to specify a default value, for example, like so:
// ES11+ console.log(null ?? 'default'); // 'default' console.log(undefined ?? 'default'); // 'default'
You can also combine the nullish coalescing operator (??
) with the optional chaining operator (?.
), to return a default value when the optional chaining operator evaluates to undefined
. For example:
// ES11+ const obj = { foo: 'bar' }; const value = obj?.nonExistent ?? 'default'; console.log(value); // 'default'
Using the Nullish Assignment Operator
The logical nullish assignment operator (??=
) allows you to only assign a value to a variable if it is nullish. For example:
// ES12+ let value; value ??= 'default'; console.log(value); // 'default'
In the example above, since the variable "value
" is undefined
, the nullish assignment operator sets its value to 'default'
.
Explicitly Checking for Nullish Value
If you are unable to support a minimum ES11, then you can explicitly check for null
and undefined
values, for example in an if/else
or a ternary, like so:
function isNullish(value) { return null === value || typeof value === 'undefined'; } const foo = null; const bar = undefined; console.log(isNullish(foo) ? 'default' : foo); // 'default' console.log(isNullish(bar) ? 'default' : bar); // 'default'
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.