15. What is optional chaining?

Optional chaining is a syntax of JavaScript, useful in checking if left side of expression equals null or undefined. If yes, right side of expression is not executed and undefined is returned.

Optional chaining can be used to acces value by key, by index or to invoke a function.

Attempt to access field from null or undefined without optional chaining will end with an error of type Cannot read property 'x' of undefined/null

const val = {a: {}}; val.a.b.c.d // Cannot read property 'c' of undefined val.a.b?.c.d // undefined val.a.b.c() // Cannot read property 'c' of undefined val.a.b.c?.() // undefined val.a.b[1] // Cannot read property '1' of undefined val.a.b?.[1] // undefined
devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.