
Posted on • Edited on • Originally published atismail9k.com
Use JavaScript Optional Chaining, Today!
Optional Chaining is a new JavaScript API that will make developers' lives easier :D. Optional Chaining is currently atStage 3, and soon enough will be part of the language itself, but we can use it, today.
In this article, I brief what isOptional Chaining
, and why it's a game-changer. I will also try to guide you on how to configure it and use it. Let's get started.
Optional Chaining
If you already know what is Optional Chaining, you can skip the overview section, and head to theConfiguration section.
Suppose you have a user, and you want to get its street address value.
conststreet=user.address.street;
This code above will work fine if the user object exists and has the address property. But as you know the real-world scenarios are not that ideal. What if the user did not add his address yet. The JavaScript compiler will throw an errorcannot read property street of undefined
To handle this issue and prevent compiler for throwing errors, I used to do something like this:
conststreet=user.address&&user.address.street;// or if need more than one value from addressconst{address={}}=user;conststreet=address.street;constcountry=address.country;
This seemed to be a good solution; but what if I want to access a deeply nested property, likeuser.subscription.attributes.name.en
. It would be more challenging.
Here comes TheOptional Chaining operator role, it allows you to optionally chain properties if it exists, without the need for assigning intermediate results in temporary variables:
constsubscription=user.subscription?.attributes?.name?.en
Also if you want to set a default value you can use the proposedNullish coalescing operator
:
constanimationDuration=response.settings?.animationDuration??300;
The Optional Chaining can also optionally call a function if it exists:
myAwesomeFunction?.();
The first time I saw this syntax, it was very odd for me. But like any new syntax, I think it will take time until my eyes used to see it. you can readhere why they had to use this syntax, for optionally calling functions.
Configuration
We can useOptional Chaining now throw the Babel compiler. I will describe how to configure:
Babel
Install@babel/plugin-proposal-optional-chaining
yarn add @babel/plugin-proposal-optional-chaining--dev# ornpminstall @babel/plugin-proposal-optional-chaining--save-dev
Add the plugin to.babelrc
config file
{"plugins":["@babel/plugin-proposal-optional-chaining"]}
ESLint
After you install the babel, you can use?.
optional chaining operator and Babel will compile it to the current working js. However, if you are using ESLint, it will not recognize the new syntax. We have tobabel-eslint
plugin in order to remove the eslint error.
yarn add babel-eslint--dev# ornpminstallbabel-eslint--save-dev
Add.eslintrc
config file
{"parser":"babel-eslint","rules":{"strict":0}}
You can now test eslint is working fine, by running this command (make sure to install eslint globally).
eslintsrc/js/**
VS Code
The last part of this setup is to config VS Code editor, althoughESLint is now aware of theoptional chaining operator, you will notice that the VS Code is still displaying an annoying warning message.
This is still an issue in VS Code validator, the workaround for this, we will have to disable the VS Code validator and work with ESLint extension.
First, make sure you have installed and activeESlint VS Code extension
Then add those configurations to the.vscode/settings.json
file
{"eslint.alwaysShowStatus":true,"eslint.autoFixOnSave":true,"javascript.validate.enable":false,"[javascript]":{"editor.formatOnSave":false,},"[javascriptreact]":{"editor.formatOnSave":false,},// requires only if you use vetur plugin"vetur.validation.script":false}
Congratulations 🥳🥳, You are now using future technologies 👽👽.
If you have any questions, or you encounter difficulty in setup the configurations, you can post it in the comments section below. Happy Codding.
PS: Optional Changing Operator, is shipped in Chrome 78, and it's available now underExperimental JavaScript
flag.
Top comments(11)

- LocationNakuru Kenya
- WorkUndergraduate student at Studying
- Joined
console.log(restaurant.openingHours[tue] ? .open);
on saving I get a gap between . and ? as seen above.
The on console this is the error.
Uncaught SyntaxError: Unexpected token '.'

Try removing the spaces between.
and?
.
console.log(restaurant.openingHours[tue]?.open);//Error: expected expression, got '.'console.log(restaurant.openingHours[tue]?.open);// Evaluates expression

- LocationNakuru Kenya
- WorkUndergraduate student at Studying
- Joined
"eslint.autoFixOnSave": true,
the above code seems to be deprecated.
kindly assist.

- LocationNakuru Kenya
- WorkUndergraduate student at Studying
- Joined
The error occurs when I save the file.
- LocationLondon, UK.
- WorkFrontend Engineer at tray.io
- Joined
Thank you!
If you use React with CRA and upgrade to CRA 3.3.0 you just have to add the .vscode./settings.json to your repository.

- Email
- LocationIstanbul, Turkey
- EducationComputer Engineering
- WorkSoftware Engineer & Tech Lead
- Joined
The main difference between the Logical OR (||
), and Nullish Coalescing Operator (??
) is the that (??
) returns its right-hand side operand when its left-hand side operand is onlynull orundefined and doesn't respect the other falsy value (e.g. 0, false, '').
See the outputs:
constx={y:{z:0}}};x?.y?.z||24;// => 24x?.y?.z??24// => 0
For sure, the behaviour for??
will be exactly the same as||
ifz isundefiend or its value isnull
For further actions, you may consider blocking this person and/orreporting abuse