Skip to content

JavaScript question mark dot | ?. operator

  • by

JavaScript question mark dot is called optional chaining operator. It allows reading the value of a property located in a Nested object.

The syntax of the optional chaining operator is as follows:

object?.property
object?.method()
  1. If object is not null or undefined, the expression evaluates to the value of object.property or object.method().
  2. If object is null or undefined, the expression evaluates to undefined without raising an error.
obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)

Simple optional chaining ?. stops the evaluation if the value before ?. is undefined or null and returns undefined.

JavaScript question mark dot

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
   const adventurer = {
    name: 'Alice',
    cat: {
      name: 'Dinah',
      sound: 'Meow'
    }
  };

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

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

</script>

</body>
</html> 

Output:

JavaScript question mark dot

Combining with Nullish Coalescing operator

The Nullish coalescing operator compares and returns the value on the right when the value on the left is null/undefined. This is used to set the default value

const data = { };
const name = data.user?.name ?? 'not found';

console.log(name); // not found

What does the question mark followed by a full stop in javascript mean?

Answer: It’s Optional chaining.

 React.useEffect(() => {
    if (route.params?.post) {
      // Post updated, do something with `route.params.post`
      // For example, send the post to the server
    }
  }, [route.params?.post]);

Why is it necessary to use the dot operator before the optional chaining?

Answer: Use the dot operator after trying to do the optional chaining.

The reason is that ? and ?. are two different things. Only the latter is Option chaining, so if you remove the period, you have a start of a ternary operation.

Also, note that The optional chaining ?. is not an operator, but a special syntax construct.

Using the optional chaining operator can lead to more concise and readable code when dealing with potentially null or undefined values.

Comment if you have any doubts or suggestions on this Js operator 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

Your email address will not be published. Required fields are marked *