Optional Chaining

Overcoming the Problem of Trust in JavaScript

Joe Morgan
The Pragmatic Programmers

--

Photo by Joshua Hoehne on Unsplash

One of the unspoken problems in development is the problem of trust. For many front-end applications, you send a request for data to an API and you get back a result. You expect that data will be a certain shape such as an object with a specific number of fields and you work with those assumptions while writing your code.

Of course, your assumptions can be wrong. And that’s when the bug reports come in.

Consider a simple application that fetches a user from an API. The standard user object might be something like this:

{
name: 'User',
contact: {
address: '221B Baker St'
}
}

In your code, you may need to want to build a string using the address:

`The address for ${user.name} is ${user.contact.address}.`

The code works for a user object as long as the object is structured the way you’d expect.

But what happens when the application changes and now can support anonymous users? It is easy to find a situation where the API returns an object with incomplete information:

{
name: 'anonymous'
}

If you try to convert this object to a string, you’ll have a big problem. True, your string would look…

--

--

Joe Morgan
The Pragmatic Programmers

I like to break things and put them back together. Author of Simplifying Javascript. Writing featured in Slate, Digital Ocean and FreeCodeCamp.