UPDATED: As of Babel 7.8.0 These features are also included by default.
Uncaught TypeError when not done right
We are going to use this mock response for the rest of the examples:
In order to avoid the common
Uncaught TypeError and get the value of
id. This pattern looks more like a conditional statement that should result in a boolean rather than being a property accessor statement but it is, the cleanest and safest native way we have today.
Or if you prefer object destructuring:
Basically what is happening here is the code block on the left side of the
&& Logical and operator is being evaluated similar to
Boolean(data) and if the value is
true it moves to evaluate the right side.
There are more ergonomic ways of doing this if you use Lodash or Ember
So how do we do the same thing using the new Optional Chaining?
It is common practice to have a default value when the value of the property we access is
undefined. Currently the common way to accomplish this is by using the
|| Logical or operator
If we are looking to get the Github username which is the
login property and set a default to the current user's username,
sedighian in this case, we will do so as below:
the second and third examples look very similar so why is Null Coalescing useful? Simply put Null Coalescing evaluates the right side of the
?? operator only if the result of the left side is
null and this gives us some protection against unintended results when dealing with valid but falsy values in our data.
For example, in many cases, we wish to an empty string
0 to the value returned rather than resulting in a falsy value and hence moving to evaluate the right side of the
|| Logical-or-operator. Now, we can use the Null Coalescing and we will not have these issues any longer as seen in the examples below:
For coming up with fallback/default values when accessing an object there are alternative ways in the form of third party libraries and in Ember's case a built-in utility.
Do not forget that Null Coalescing is for more than coming up with a default value to assign to a variable, it is a new alternative way to execute a code block given a
undefined value. For example:
What to watch out for...
Order matters when using
? in Optional Chaining
Optional Chaining does not protect you against incorrectly invoking a non-function
Null Coalescing is not an apple to apple to
EmberObject.getWithDefault. The main difference is in how Null Coalescing treats
null vs. these two utilities.
TypeScript 3.7 release notes
Babel 7.8.0 Release notes
Top comments (1)
These are very nice features!