Answers for "optional chaining javascript"

4

conditional chaining chrome

const nameLength = db?.user?.name?.length; // property
const adminOption = db?.user?.validateAdminAndGetPrefs?.().option; // functions
const optionLength = db?.user?.preferences?.[optionName].length; // dynamic property
const userName = usersArray?.[userIndex].name; // on arrays
Posted by: Guest on June-16-2020
4

optional chaining

let myMap = new Map();
myMap.set("foo", {name: "baz", desc: "inga"});

let nameBar = myMap.get("bar")?.name;
Posted by: Guest on February-25-2020
2

optional chain operator

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined
Posted by: Guest on October-12-2020
0

optional chaining javascript

Optional chaining: (?.)

The optional chaining operator (?.) enables you to 
read the value of a property located deep within a 
chain of connected objects without having to 
check that each reference in the chain is valid.

The ?. operator is like the . chaining operator, 
except that instead of causing an error if a reference 
is nullish (null or undefined), the expression returns 
a value of undefined. 

When used with function calls, 
it returns undefined if the given function does not exist.

Example:

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// output: undefined

console.log(adventurer.someNonExistentMethod?.());
// output: undefined
Posted by: Guest on July-09-2021
2

optional chaining

/* 
* optional chaining (?.) allows me to write code that stops 
* running when we encounter a null or undefined value
*/

function tryGetFirstElement<T>(arr?: T[]) {
    return arr?.[0];
    // equivalent to
    //   return (arr === null || arr === undefined) ?
    //       undefined :
    //       arr[0];
}
Posted by: Guest on March-02-2020
0

optional chaining

const greeting = object?.deepProp?.deeperProp?.greet
Posted by: Guest on June-25-2021

Browse Popular Code Answers by Language