You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
This repository was archived by the owner on Jan 28, 2023. It is now read-only.
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.
constresponse={settings: {nullValue: null,height: 400,animationDuration: 0,headerText: '',showSplashScreen: false}};constundefinedValue=response.settings.undefinedValue||'some other default';// result: 'some other default'constnullValue=response.settings.nullValue||'some other default';// result: 'some other default'
This works well for the common case of null and undefined values, but there are a number of falsy values that might produce surprising results:
constheaderText=response.settings.headerText||'Hello, world!';// Potentially unintended. '' is falsy, result: 'Hello, world!'constanimationDuration=response.settings.animationDuration||300;// Potentially unintended. 0 is falsy, result: 300constshowSplashScreen=response.settings.showSplashScreen||true;// Potentially unintended. false is falsy, result: true
The nullary coalescing operator is intended to handle these cases better and serves as an equality check against nullary values (null or undefined).
Syntax
Base case. If the expression at the left-hand side of the ?? operator evaluates to undefined or null, its right-hand side is returned.
constresponse={settings: {nullValue: null,height: 400,animationDuration: 0,headerText: '',showSplashScreen: false}};constundefinedValue=response.settings.undefinedValue??'some other default';// result: 'some other default'constnullValue=response.settings.nullValue??'some other default';// result: 'some other default'constheaderText=response.settings.headerText??'Hello, world!';// result: ''constanimationDuration=response.settings.animationDuration??300;// result: 0constshowSplashScreen=response.settings.showSplashScreen??true;// result: false
Notes
While this proposal specifically calls out null and undefined values, the intent is to provide a complementary operator to the optional chaining operator. This proposal will update to match the semantics of that operator.