[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Optional_chaining [Back]  [Original]

- JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2020 ..

?. , , . ?. ., , , , , null undefined. undefined.

, , , - .

In this article

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

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

console.log(adventurer.someNonExistentMethod?.());
// Expected output: undefined

js
obj?.prop;
obj?.[expr];
arr?.[index];
func?.(args);

, , - ( ) undefined null.

, obj, . , :

js
let nestedProp = obj.first && obj.first.second;

obj.first.second obj.first, , obj.first null undefined, TypeError.

, (?.) obj.first obj.first.second:

js
let nestedProp = obj.first?.second;

?. ., JavaScript obj.first obj.first.second. obj.first null undefined, undefined.

( ):

js
let temp = obj.first;
let nestedProp = temp === null || temp === undefined ? undefined : temp.second;

?., , . , , API, - .

?. , undefined, , :

js
let result = someInterface.customMethod?.();

: , , x.y?.() TypeError (x.y ).

-

- , , . ?., :

js
//   ES2019
function doSomething(onContent, onError) {
  try {
    // ...  -  
  } catch (err) {
    if (onError) {
      // ,   onError
      onError(err.message);
    }
  }
}
js
//     
function doSomething(onContent, onError) {
  try {
    // ...  -  
  } catch (err) {
    onError?.(err.message); //   ,  onError  undefined
  }
}

, :

js
let nestedProp = obj?.["prop" + "Name"];

name bar Map. , ; nameBar undefined.

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

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

, null undefined, . :

js
let potentiallyNullObj = null;
let x = 0;
let prop = potentiallyNullObj?.[x++];

console.log(x); // 0, .. x   

:

js
let customer = {
  name: "Carl",
  details: {
    age: 82,
    location: "Paradise Falls", //   
  },
};
let customerCity = customer.details?.address?.city;

//       
let duration = vacations.trip?.getTime?.();

??

?? :

js
let customer = {
  name: "Carl",
  details: { age: 82 },
};
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity); // Unknown city

Specification
ECMAScript 2027 LanguageSpecification
# prod-OptionalExpression


Web Proxy Viewer  |  New URL  |  Original Page