Nearby lessons

6 of 22

Advanced JavaScript: Optional Chaining (?.)

๐Ÿ“Œ What is Optional Chaining?

Optional chaining ?. is a feature in JavaScript that allows you to safely access deeply nested properties of an object without having to explicitly check if each reference in the chain is valid.

It prevents runtime errors caused by accessing properties of null or undefined.

1๏ธโƒฃ Basic Syntax

Use ?. to access a property only if the preceding object is not null or undefined.

  • Safe way to access deeply nested object properties
  • Returns undefined instead of throwing an error if any part is null/undefined
  • Can be used with objects, arrays, and functions
Code Example
PREVIEW READY
Loading Editor...
Live Preview

2๏ธโƒฃ Without Optional Chaining (Old Method)

Before optional chaining, developers had to use logical AND (&&) checks to access nested properties.

Code Example
PREVIEW READY
Loading Editor...
Live Preview

3๏ธโƒฃ Optional Chaining with Arrays

You can use optional chaining to safely access elements of an array that might be null or undefined.

Code Example
PREVIEW READY
Loading Editor...
Live Preview

4๏ธโƒฃ Optional Chaining with Functions

If a method or function might not exist, use optional chaining before calling it.

Code Example
PREVIEW READY
Loading Editor...
Live Preview

๐Ÿง  Test Your Knowledge

3 Questions

Progress: 0 / 3
Keep Going!AJS - Nullish Coalescing