Learn JavaScript
Optional Chaining
39.7
Lesson

Other variants of Optional Chaining

Optional chaining ?. also works with functions and square brackets.

We can use ?.() to execute a function that may not exist.

In the example given above, since the message function exists in the userSam object it executes. The message function returns undefined because it does not exist in the userOliver object.

We can use square brackets ?.[] to access the properties of an object. If the property does not exist, it returns undefined.

In the example given above, the name property exists in the userSam object and it does not exist in the userOliver object. Therefore, the first console.log statement returns Sam Smith and the second console.log statement returns undefined.

We can use optional chaining ?. with delete to remove an existing property from an object.

In the example given above, we are removing the age property from the userSam object.