Skip to content

JavaScript Optional Chaining | Use and Examples

  • by

Using JavaScript optional chaining operator (?.) can get the value of a property located deep objects (Nested Object) without having to check that if each reference in the chain is null or undefined..

obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)

This is a safe way to access nested object properties, even if an intermediate property doesn’t exist.

const value = obj?.propOne?.propTwo?.propThree?.lastProp;

Here’s the basic syntax of Optional Chaining

object?.property
object?.method()

The ?. operator is used in between the object and the property/method you want to access. If the object is not null or undefined, the property or method is accessed, and the expression evaluates to its value. If the object is null or undefined, the expression returns undefined without throwing an error.

JavaScript Optional Chaining

Simple example code If one of the references in the chain is null or undefined, the optional chaining operator (?.) will short circuit and return undefined.

<!DOCTYPE html>
<html>
<body>

  <script>
   const adventurer = {
    name: 'John',
    dog: {
      name: 'Tommy',
      sound: 'Bhow Bhow...'
    }
  };

  const catName = adventurer.cat?.name;
  console.log(catName);

  const dogName = adventurer.dog?.name;
  console.log(dogName);
  console.log(adventurer.dog?.sound);

</script>

</body>
</html> 

Output:

JavaScript Optional Chaining

Optional Chaining + Nullish Coalescing

Optional chaining pairs well with nullish coalescing ?? to provide fallback values.

const data = obj?.prop ?? "fallback string";
const data = obj?.prop?.func() ?? fallbackFunc();

If the item to the left of ?? is nullish, the item to the right will be returned.

Summary

We should use ?. only where it’s ok that something doesn’t exist.

For example, if according to our code logic user object must exist, but address is optional, then we should write user.address?.street, but not user?.address?.street.

  1. obj?.prop – returns obj.prop if obj exists, otherwise undefined.
  2. obj?.[prop] – returns obj[prop] if obj exists, otherwise undefined.
  3. obj.method?.() – calls obj.method() if obj.method exists, otherwise returns undefined.

Do comment if you have any doubts or suggestions on this Js topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading