Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

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
Comment

optional chaining in js

// Optional chaining

// Basically Optional chaining is use nested destructuring like shown below !!

// const obj = [{
//  obj: {
//   obj: "FAhad",
//  },
//}]

// console.log(obj[0]?.obj?.obj);

// Like as you watched that How we are getting the elements from obj

const obj = [{
  obj: {
  },
}]

console.log(obj[0]?.obj?.obj);

// It's retruning undefined just because of optional chaining otherwise it'll return an error 

// ----------THE END----------
Comment

optional chain operator

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

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

optional chaining

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

let nameBar = myMap.get("bar")?.name;
Comment

Optional Chaining javascript

The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.

For example, consider an object obj which has a nested structure. Without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as:

let nestedProp = obj.first && obj.first.second;
Copy to Clipboard
The value of obj.first is confirmed to be non-null (and non-undefined) before then accessing the value of obj.first.second. This prevents the error that would occur if you accessed obj.first.second directly without testing obj.first.

With the optional chaining operator (?.), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second:

let nestedProp = obj.first?.second;
Copy to Clipboard
By using the ?. operator instead of just ., JavaScript knows to implicitly check to be sure obj.first is not null or undefined before attempting to access obj.first.second. If obj.first is null or undefined, the expression automatically short-circuits, returning undefined.

This is equivalent to the following, except that the temporary variable is in fact not created:

let temp = obj.first;
let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);
Comment

Optional chaining

let x = foo?.bar();

if (foo?.bar?.baz) { // ... }
Comment

optional chaining

const greeting = object?.deepProp?.deeperProp?.greet
Comment

optional chaining in javascript

method1?.method2.method3
Comment

optional-chaining operator

if (user?.team?.subscription?.invoices) {
  //
}
Comment

js optional chaining array

// For arrays
const friendAtPositionZeroIfItExists = user?.friends?.[0]
Comment

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];
}
Comment

optional chaining

const array = [1,2,3,4,5];
let arrItem = array?.[4]; 

console.log(arrItem); /// 5
Comment

PREVIOUS NEXT
Code Example
Javascript :: captalize first letter javascript 
Javascript :: mongoose in nodem js 
Javascript :: Adding whitespace to the left of the string in JavaScript 
Javascript :: navigator user media check if camera is availabe 
Javascript :: give a prop only if pass condition 
Javascript :: post method in reactjs hooks. 
Javascript :: jquery get parameter from url 
Javascript :: js do...while 
Javascript :: scroll up btn 
Javascript :: react : calling APIs after render 
Javascript :: use of this keyword in js 
Javascript :: sort array in javascript 
Javascript :: destructured object 
Javascript :: how to append item to an array in foreach javascript 
Javascript :: how to loop over an array in js 
Javascript :: check phone number validation in javascript 
Javascript :: Add additional css class name in react app 
Javascript :: switch javascript 
Javascript :: mogoosejs 
Javascript :: render partial in js.erb 
Javascript :: simple express server 
Javascript :: how to make javascript function consise 
Javascript :: .includes meaning in javascript 
Javascript :: addAndRemoveClassJquery 
Javascript :: math floor html 
Javascript :: antd search in select 
Javascript :: webpac-merge 
Javascript :: trigger sweet alert through javascript 
Javascript :: file_get_contents in javascript 
Javascript :: how to write a funcat in javascript 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =