โoptional chaining (?., ?.[])
`obj ?. prop` syntax. ๐ง under construction -> SyntaxError: Unexpected token
Last updated
Was this helpful?
`obj ?. prop` syntax. ๐ง under construction -> SyntaxError: Unexpected token
Last updated
Was this helpful?
Was this helpful?
JS โฉ statement โฉ expression โฉ operator โฉ left-hand side โฉ
(operator) (โญ๏ธ ES2020) (๐ chaining rules | table of operators )
obj
?.
prop
returns undefined if obj
is nullish.
obj ?. prop // dot notation
obj ?. [ expr ] // bracket notation
func ?. ( args ) // conditional invocation
๐ฏ synonyms๏ผ"conditional property access", "optional chaining"
codepen๏ผoptional chaining
// โญ๏ธ 1. prop: invalid identifier
// ------------------------------
undeclared ?. 1 = 'bad'; // โ SyntaxError: Unexpected token
// ^
// โญ๏ธ 2. obj: "undeclared"
// -------------------------------
undeclared ?. prop; // โ ReferenceError: 'undeclared' is not defined
// โญ๏ธ 3. obj: "nullish"
// -------------------------------
// ๐ก๏ธ "?." only protects "nullish obj" and "direct prop"
// โ "." provides NO protection.
// โ "root" object is NEVER protected.
jane . boyfriend ?. name // โ
boyfriend: non-nullish, ok.
// โฐโโโโโโโฏ โฐ๐ก๏ธโฏ
jane . boyfriend ?. money . more // โ
money: direct prop, protected.
// โฐโโโโโโโฏ โฐโ๐ก๏ธโโฏ โฐโโฏ // โ more: not protected, error may occur.
user?.name // โ
read if exists
delete user?.name // โ
delete if exists.
user?.name = "John" // โ SyntaxError
// Invalid left-hand side in assignment
// this is literally `undefine = "John"`โ๏ธ
obj ?. [ expr ] // โ
there's a tiny "dot" โ๏ธ
obj ? [ expr ] // โ wrong syntax
let a = { b: null };
a.b?.c.d, // โ
this is OK (โญ "short-circuiting" works.)
// โญโ UD โโฎ // UD: undefined
(a.b?.c).d, // โ DON'T DO THIS! (โ TypeErrorโ)
// ^
const city = user ?. city ?? "Unknown city"
// โฐโโ O.C. โโโฏ โฐโ default โโโฏ
let user = {};
user.address; // undefined
// โ TypeError:
// ----------------------------------------------
user.address.street; // Cannot read property 'street' of undefined
// ^^^^^^
// โญ๏ธ 1. using (?:) operator
// -------------------------
// โข access `user.address.street`
user.address ? user.address.street : undefined, // undefined
// โข access `user.address.street.name`
user.address
? (user.address.street ? user.address.street.name : null)
: null; // null
// โญ๏ธ 2. using (&&) operator
// -------------------------
// โข access `user.address.street.name`
user.address
&& user.address.street
&& user.address.street.name; // undefined