Skip to content

Instantly share code, notes, and snippets.

@psenger
Last active January 14, 2023 07:03
Show Gist options
  • Select an option

  • Save psenger/f05a1cfd814692be1565db40827f7288 to your computer and use it in GitHub Desktop.

Select an option

Save psenger/f05a1cfd814692be1565db40827f7288 to your computer and use it in GitHub Desktop.
[Optional Chaining (?.) Done Right] #JavaScript #WIP

WORK IN PROGRESS

Optional Chaining (?.) Done Right

Optional Chaining : The optional chaining ?. operator accesses an object's property or calls a function. If the object accessed or function called is undefined or null, it returns undefined instead of throwing an error.

It should be noted, that this ES6 feature has been the topic of debate amongst established experts such as Kyle Simpson. His and other's opinions are justified. Kyle dislike is so strong he wrote an ESLINT Plugin. However, its my opinion this doesnt mean that the feature is without merits. JavaScript by its very nature is filled with issues, knowing what they are and avoiding or using them when appropiate is a pragmatic aproach.

Its a common misconception that Optional Chaing was intended for replacing short-circuting

EG:

// If the object i
const result = obj.func && obj.func(42)
// could be written 
const result = obj?.func(42)

However, the problem with this is Optional Chaining Operator only stops at null and undefined values, not falsey ( such as false, '', NAN, or 0 ). This is the same with ES6 Optional Parameter feature.

Therefore you should avoid

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment