Optional Chaining in JavaScript

 

Optional Chaining in JavaScript 

 

Optional chaining is the process of querying and calling properties, methods, and indexes on an optional that may currently be null. If the optional contains a value, the property, method, or subscript call will succeed; if the optional value is null, calls to the property, method, or subscript will return null. Multiple queries can be chained together and the entire chain will fail without issue if any member of the chain is null.

 

Optional chaining is a neat syntax that allows us to short circuit an expression if we encounter a null or undefined value.

 

Let bookName = books && books.name;

 

The next few code snippets show how optional chaining differs from forced unpacking and allows you to check for success.

 

class Person {
var residence: Residence?
}

class Residence {
var numberOfRooms = 1
}

 

Residence instances have a single Int property named numberOfRooms with a default value of 1. Person instances have an optional residence property of type Residence?.

If you create a new instance of a person, its residence property is initialized to zero by default because it is optional. In the code below, John has a residential property value of zero:

let John = Person()

If you try to access the numberOfRooms property of this person's residence by placing an exclamation point after the residence to force its value to be expanded, you will throw a runtime error because there is no residence value to expand:

let roomCount = john.residence!.numberOfRooms

 

The above code succeeds when john.residence is non-zero and sets roomCount to an Int containing the appropriate number of rooms. However, this code will always throw a runtime error when the residence is null, as shown above.


Tags:

Share:

Related posts