Nullish Coalescing operator (??) for JavaScript - Concept:
When performing property accesses, it is often desired to provide a default value if the result of that property access is `null` or `undefined`. At present, a typical way to express this intent in JavaScript is by using the || operator.
const response = {
settings: {
nullValue: null,
height: 400,
animationDuration: 0,
headerText: '',
showSplashScreen: false
}
};
Accessing the object property and assigning default value
Example(Common case)
const undefinedValue = response.settings.undefinedValue || 'some other default'; // result: 'some other default'
const nullValue = response.settings.nullValue || 'some other default'; // result: 'some other default'
While above solution works well for the common case of `null` and `undefined` values, but there are a number of falsy values that might produce surprising results:
Example (Problem):
const headerText = response.settings.headerText || 'Hello, world!'; // Potentially unintended. '' is falsy, result: 'Hello, world!'
const animationDuration = response.settings.animationDuration || 300; // Potentially unintended. 0 is falsy, result: 300
const showSplashScreen = response.settings.showSplashScreen || true; // Potentially unintended. false is falsy, result: true
So here is the `nullary coalescing operator (??)` is intended to handle these cases better and serves as an equality check against nullary values (null or undefined).
Example (Solution)
const undefinedValue = response.settings.undefinedValue ?? 'some other default'; // result: 'some other default'
const nullValue = response.settings.nullValue ?? 'some other default'; // result: 'some other default'
const headerText = response.settings.headerText ?? 'Hello, world!'; // result: ''
const animationDuration = response.settings.animationDuration ?? 300; // result: 0
const showSplashScreen = response.settings.showSplashScreen ?? true; // result: false
In the above example we are getting what we are expecting to be. So use nullary coalescing operator (??) for avoid such cases.
Thanks for reading. Please feel free to drop your comment and feedback,
Software Engineer at iCIMS INDIA
3 年Great job ???? very nicely explain?