Explain Codes LogoExplain Codes Logo

How can I use optional chaining with arrays and functions?

javascript
optional-chaining
javascript-features
best-practices
Anton ShumikhinbyAnton Shumikhin·Feb 11, 2025
TLDR

To safely access array elements or invoke functions use ?..

Array element access:

const element = arr?.[index]; // No Scarlett Johansson error plays if index is out-of-bounds, just undefined.

Function invocation:

const result = obj.method?.(...args); // Undefined. Like my mind when the method doesn't exist.

Optional chaining (?.) is a feature in JavaScript to safely access nested object properties and invocations if any in the chain can possibly produce undefined or null.

Key scenarios and usage

Safely traversing object properties

Optional chaining allows you to delve down into deeply nested property paths without the fear of causing a runtime error:

let name = user?.profile?.name; // If `profile` isn't there, `name` will be peacefully undefined.

Guarded function invocation

Use optional chaining when calling functions at uncertain places to avoid a runtime error:

obj.questionableMethod?.(); // Does nothing if `questionableMethod` is a no-show.

Array elements retrieval

Retrieving items from an array especially after handling methods like filter (that always return an array) just became error-free:

const awaitedMatch = myArray?.filter(x => x === soughtValue)?.[0]; // Safely returns undefined if no matching items exist, much like my missing socks.

Handling React components and hooks

Perform status checks in your React hooks or on uncertain props with more confidence:

const isOnline = useStatusHook?.('userID_123')?.isOnline; // Safeguard against a missing hook and a runtime hook. const displayName = props?.user?.name; // Safe if user is a ghost prop.

Do's and don'ts

There are a few best practices and caveats worth remembering with optional chaining:

  • Resistance to excessive use: Reduces readability and bypasses potential structural issues in your code.
  • Runtime errors: JS won't blow a whistle for out-of-bounds array access. Just when you attempt to use the resultant object.
  • Handle with care: Be mindful of functions with side effects when using optional chaining.
  • Verify compatibility: Check for support in your target environment because not all JavaScript engines run optional chaining smoothly (I'm looking at you, IE!).

Power-up with optional chaining

For advanced usage, let's explore some scenarios:

Combination with nullish coalescing

Optional chaining and nullish coalescing (??) together can be a dynamic duo, helping assign default values when a nullish value (null or undefined) is encountered:

let name = user?.name ?? 'Incognito'; // 'Incognito' if `name` isn't there or is null, not hiding behind `false`, `NaN`, or `0`.

Existence verification for method invocation

Optional chaining shortens and simplifies your code when verifying the existence of methods:

if (typeof obj.method === 'function') { obj.method(args); } // This chunk of wisdom can be shortened to: obj.method?.(args);

Nested array values retrieval

Avoid undefined monstrosities when dealing with multidimensional arrays:

const nestedValue = matrix?.[x]?.[y]; // Does not glitch if `matrix[x]` is out of bounds or simply doesn't hold the key to `y`.

Dynamic property access

Flexible enough for dynamic property access as well:

const property = 'name'; const value = obj?.[property]; // Undefined if `obj` doesn't host a property `name`, or it did but forgot to send the invite.