UPDATED: As of Babel 7.8.0 These features are also included by default.
Uncaught TypeError when not done right
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.
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
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:
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.