DEV Community

Discussion on: 😰 Optional chaining trap !

Collapse
 
elmuerte profile image
Michiel Hendriks

I like the safe navigation operator, but I fear its usage. One level is ok, two might be acceptable, but beyond that you are doing things wrong.

It is nice for templates. But for normal programming? What are you doing so deep in an object structure?

Collapse
 
woubuc profile image
Wouter

I agree, overuse of optional chaining and null-coalescing is something that code styles and guidelines will have to limit.

As I see it, it will mostly be useful for things like options objects loaded from a JSON or YML file, where you have settings that may or may not be set, and often 1-3 levels deep. Or when loading documents from a MongoDB where you have set of properties and data that may or may not be there.

Collapse
 
thekashey profile image
Anton Korzunov

What are you doing so deep in an object structure?

Exactly the point! If a top level key is not accessible, then:

  • why it's not accessible? it is null, undefined, so you can't go deeper, or it string, and your data type is too mutable? It's a quite popular to have something which could be "string/object" or "object/function". Why?
  • then may be another keys from the same location, you are going to read a moment later is also not accessible. Why? May be some decision should be made a bit before? Why?
  • and of course - why some data (you got from the network) might unpredictable not exists, and you are not "ready" for this. Why?