The Quick Answer
My Video illustrating both features: https://www.youtube.com/watch?v=1Vho--vDhQM
You sometimes will get runtime errors when you try to refer to an object property that does not exist. I have this issue often times with iterating arrays from API calls where some items in the array may not have a particular property.
in this situation I would have to do the following:
variable = object.property;
With optional chaining, I can do the following…
variable = object?.property
The ‘?’ at the end of the property tell the interpreter to return null if the property doesn’t exist avoiding the runtime errors of the past and just looking a lot more elegant.
When establish a default value when there was uncertainty if the desired assignment has a value would usually be done like so…
myNewVariables = possibleVariable || defaultValue;
If possibleVariable had a truthy value it would assign it, if not, defaultValue would be assigned. The problem is the situations in which you may want to assign 0 or false. This method would evaluate those as falsely and assign the default value.
This is our new solution!
myNewVariables = possibleVariable ?? defaultValue;
This new ‘??’ operator will only return the default value if the first express is null or undefined, so 0 and false would be assigned.