0

What is the Best way to get Deeply nested defaults.

Currently I am using below code to get bucket value of check_ab and I am seeting it to default value of A, which is hampering readability

 settings: { experiments: { check_ab: { bucket: abvalue = 'A' } = {} } = {} } = {},

How to clearly extract and set safe defaults

user3530827
  • 143
  • 2
  • 8

1 Answers1

1

Maybe destructure it in multiple lines. Thats not shorter, but more readable imo:

  function set(settings = {}) {
     const { experiments = {} } = settings:
     const { check_ab = {} } = experiments;
     const abvalue = check_ab.bucket || "A";
 }

In a further js version you could do:

 function set(settings) {
  const abvalue = settings?.experiments?.check_ab?.bucket || "A";
 }
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
  • your first option is clear, but wanted something in a line or 2, the below option would probably be allowed in future js versions, so can't use it for now – user3530827 Mar 29 '18 at 11:59