Optional chaining is a game changer for everyone who uses Javascript. It is just as important as the arrow function or let and const. Let’s talk about what it solves, how it works, and how it makes your life easier.
The problem
Imagine the following scenario:
You are using snippet code to load data from an API. The returned data is deeply nested objects, which means you need to iterate over long object properties.
// API response object
const person = {
details: {
name: {
firstName: "Michael".lastName: "Lampe",}},jobs: [
"Senior Full Stack Web Developer"."Freelancer"]}// Getting the firstName
const personFirstName = person.details.name.firstName;
Copy the code
For now, it’s good to keep that code. However, there is a better solution, which is as follows:
// Checking if firstName exists
if( person &&
person.details &&
person.details.name ) {
const personFirstName = person.details.name.firstName || 'stranger';
}
Copy the code
As you can see in the example, even simple things, like getting a person’s name, can be difficult to get right.
So, that’s why we use libraries like LoDash to handle things like this:
_.get(person, 'details.name.firstName'.'stranger');
Copy the code
Lodash makes your code more readable, but you have to introduce a lot of dependencies into your code base. You need to update it, and then, if you’re working in a team, you need to promote the use of it in the team. So, it’s not an ideal solution either.
The solution
Alternative chains provide a solution to these (in addition to the team’s problems).
How does it work
The new syntax for optional chains may seem strange to you for the first time, but you’ll get used to it after a few minutes.
constpersonFirstName = person? .details?.name?.firstName;Copy the code
Okay, you probably have a lot of question marks in your head right now. Grammatical above? It’s something new. That’s what you have to think about. Before the attribute, there is? Does the attribute person exist? Or, more javascript — is the value of the person property null or undefined? If so, undefined is returned instead of an error. So personFirstName will return undefined. For the details? And the name? Repeated inquiries are made. If either value is null or undefined, then personFirstName returns undefined. This is called short-circuiting. Once javascript finds a value of null or undefined, it shorts out and doesn’t go any further.
The default value
We also need to learn about the Nullish coalescing operator. Okay, that sounds hard to learn. But actually, it’s not hard at all. Let’s look at the following example:
constpersonFirstName = person? .details?.name?.firstName ??'stranger';
Copy the code
Nullish coalescing operator To represent. It’s also easy to read. If?? The content returned on the left side is undefined, so the personFirstName will return?? The value on the right hand side is assigned to it. It’s too easy.
Dynamic properties
Sometimes you need to get dynamic values. It could be the value of an array or a dynamic property of an object.
const jobNumber = 1; const secondJob = person? .jobs? .[jobNumber] ?? 'none';Copy the code
The important thing to understand here is jobs? .[jobNumber], which expresses the same as jobs[jobNumber], but does not throw an error; Instead, it returns None.
A function or method call
Sometimes, you’re dealing with objects, and you don’t know if they have methods. Here we can use, right? .() syntax or with arguments? .({some: ‘args’}) syntax. It works according to your needs. If the method does not exist in that object, it returns undefined.
constcurrentJob = person? .jobs.getCurrentJob? . ()??'none';
Copy the code
In the example above, if there is no getCurrentJob method, currentJob will return None.
Start using it today
No browser currently supports this feature -Babel does the conversion.
There is already a babel.js plug-in, which is easy to integrate if you already have Babel Settings.
babel-plugin-proposal-optional-chaining
Reference and postscript
- Original text: dev. To/lampewebdev…
- First article: github.com/reng99/blog…
- More: github.com/reng99/blog…