# Optional Chaining Operator in JavaScript

Source: https://tpiros.dev/blog/optional-chaining-operator-in-javascript

Let's look at a proposal that brings optional chaining to JavaScript.

# What Is Optional Chaining?

Optional chaining already exists in other languages like C# (where they call it the `null-conditional operator`). It's a safety mechanism that lets you check whether an object exists before accessing its properties.

Here's how C# handles it:

```javascript
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public Person Spouse { get; set; }
}

var spouseName = p?.Spouse?.FirstName; // null-conditional operator
var spouseName = (p == null) ? null : (p.Spouse == null) ? null : p.Spouse.FirstName; // without the null-conditional operator
```

# Optional Chaining in JavaScript

The TC39 committee recently moved the proposal for optional chaining to Stage 3:

> WE JUST MOVED OPTIONAL CHAINING IN JS TO STAGE 3 🎉🎉🎉🎉🎉🎉🎉
> &mdash; Daniel Rosenwasser (@drosenwasser) [July 25, 2019](https://twitter.com/drosenwasser/status/1154456633642119168?ref_src=twsrc%5Etfw)

So what does this mean for JavaScript developers?

Right now, to check a property nested inside another object, you need to verify the parent exists first:

```javascript
/*
Given the following structure:
{
  "user": {
    "name": "John",
    "photo": "john.png",
    "location": {
      "city": "London",
      "country": "UK"
    }
  }
}
  */
const city = user.location && user.location.city;
```

Skip that check and you'll hit Uncaught TypeErrors when you try to operate on a property that doesn't exist:

```javascript
const city = user.location.city.toUpperCase(); // throws Uncaught TypeError if location.city doesn't exist
```

With the Optional Chaining Operator (denoted by `?`), you can handle this cleanly:

```javascript
const city = user.location?.city;
```

The Optional Chaining Operator lets you safely check for the existence of deeply nested properties in objects.

One thing to watch: the correct syntax is `?.` (the question mark and dot together). Getting this wrong will trip you up:

```javascript
const firstElement = someObject?.someArray?.[0] // will work
const secondElement = someObject?.someArray?[1] // nope - incorrect syntax, not using ?.
```

Under the hood, the operator checks whether the value on the left-hand side is `null` or `undefined`. If it is, it returns `undefined`. Otherwise, it keeps evaluating the expression and returns the correct value.

> Note that in Angular we can use a similar feature.

# Conclusion

The Optional Chaining Operator will be a genuine help for JavaScript developers because it removes unnecessary null checks on objects. Here's hoping it gets added to the language soon.
