简体   繁体   中英

js: proper way to use optional chaining?

I am a little confused as to where in a nested object the optional chaining is used...if I have a nested object like this:

obj = {
   obj1: {
     name: "o",
     obj2: {
       name: "X",
       obj3: {
         name: "Y",
         obj4: {
         }
       }
     }
   }
}

should I just be using ?. at every level for safety like:

obj?.obj1?.obj?.obj2?.obj3?.obj4 

or would I only need it at the top level?

You only need to use it right after a property that might be nullish.

For example, if obj may either be undefined, or the object in the question, you'd do:

obj?.obj1.obj2.obj3.obj4

 const getVal = obj => obj?.obj1.obj2.obj3.obj4; console.log(getVal({ obj1: { name: "o", obj2: { name: "X", obj3: { name: "Y", obj4: { } } } } })); console.log(getVal());

Or, if obj is always defined, and the only thing that might not exist is the nested obj3 property, you'd do:

obj.obj1.obj2.obj3?.obj4 

 const getVal = obj => obj.obj1.obj2.obj3?.obj4; console.log(getVal({ obj1: { name: "o", obj2: { name: "X", obj3: { name: "Y", obj4: { } } } } })); console.log(getVal({ obj1: { name: "o", obj2: { name: "X", } } }));

Use ?. right after every possibly-nullish expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM