| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Operators/Optional_chaining | [Back] [Original] |
Get to know MDN better
This page was translated from English by the community. Learn more and join the MDN Web Docs community.
This feature is well established and works across many devices and browser versions. Its been available across browsers since 2020 ..
?. , , . ?. ., , , , , null undefined. undefined.
, , , - .
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
obj?.prop;
obj?.[expr];
arr?.[index];
func?.(args);
, , - ( ) undefined null.
, obj, . , :
let nestedProp = obj.first && obj.first.second;
obj.first.second obj.first, , obj.first null undefined, TypeError.
, (?.) obj.first obj.first.second:
let nestedProp = obj.first?.second;
?. ., JavaScript obj.first obj.first.second. obj.first null undefined, undefined.
( ):
let temp = obj.first;
let nestedProp = temp === null || temp === undefined ? undefined : temp.second;
?., , . , , API, - .
?. , undefined, , :
let result = someInterface.customMethod?.();
:
, , x.y?.() TypeError (x.y ).
// ES2019
function doSomething(onContent, onError) {
try {
// ... -
} catch (err) {
if (onError) {
// , onError
onError(err.message);
}
}
}
//
function doSomething(onContent, onError) {
try {
// ... -
} catch (err) {
onError?.(err.message); // , onError undefined
}
}
let nestedProp = obj?.["prop" + "Name"];
name bar Map. , ; nameBar undefined.
let myMap = new Map();
myMap.set("foo", { name: "baz", desc: "inga" });
let nameBar = myMap.get("bar")?.name;
, null undefined, . :
let potentiallyNullObj = null;
let x = 0;
let prop = potentiallyNullObj?.[x++];
console.log(x); // 0, .. x
:
let customer = {
name: "Carl",
details: {
age: 82,
location: "Paradise Falls", //
},
};
let customerCity = customer.details?.address?.city;
//
let duration = vacations.trip?.getTime?.();
?? :
let customer = {
name: "Carl",
details: { age: 82 },
};
const customerCity = customer?.city ?? "Unknown city";
console.log(customerCity); // Unknown city
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # prod-OptionalExpression |
This page was last modified on 29 . 2026 . by MDN contributors.
Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |