Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Use JavaScript Optional Chaining, Today!
Abdelrahman Ismail
Abdelrahman Ismail

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;
Enter fullscreen modeExit fullscreen mode

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

cannot read property street of undefined error

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;
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode

Also if you want to set a default value you can use the proposedNullish coalescing operator:

constanimationDuration=response.settings?.animationDuration??300;
Enter fullscreen modeExit fullscreen mode

The Optional Chaining can also optionally call a function if it exists:

myAwesomeFunction?.();
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode

Add the plugin to.babelrc config file

{"plugins":["@babel/plugin-proposal-optional-chaining"]}
Enter fullscreen modeExit fullscreen mode

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.

eslint error

yarn add babel-eslint--dev# ornpminstallbabel-eslint--save-dev
Enter fullscreen modeExit fullscreen mode

Add.eslintrc config file

{"parser":"babel-eslint","rules":{"strict":0}}
Enter fullscreen modeExit fullscreen mode

You can now test eslint is working fine, by running this command (make sure to install eslint globally).

eslintsrc/js/**
Enter fullscreen modeExit fullscreen mode

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.

vs code error

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}
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
njugunapm233 profile image
njugunapm233
I am an aspiring software engineer in web development and Android programming.
  • Location
    Nakuru Kenya
  • Work
    Undergraduate 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 '.'

CollapseExpand
 
ender_minyard profile image
ender minyard
💻➕📱
  • Joined

Try removing the spaces between. and?.

console.log(restaurant.openingHours[tue]?.open);//Error: expected expression, got '.'console.log(restaurant.openingHours[tue]?.open);// Evaluates expression
Enter fullscreen modeExit fullscreen mode
CollapseExpand
 
njugunapm233 profile image
njugunapm233
I am an aspiring software engineer in web development and Android programming.
  • Location
    Nakuru Kenya
  • Work
    Undergraduate student at Studying
  • Joined

"eslint.autoFixOnSave": true,

the above code seems to be deprecated.
kindly assist.

Thread Thread
 
ender_minyard profile image
ender minyard
💻➕📱
  • Joined

Can you disable ESLint? ESLint may be causing the error.

CollapseExpand
 
njugunapm233 profile image
njugunapm233
I am an aspiring software engineer in web development and Android programming.
  • Location
    Nakuru Kenya
  • Work
    Undergraduate student at Studying
  • Joined

The error occurs when I save the file.

CollapseExpand
 
floroz profile image
Daniele Tortora
I am a Frontend Engineer who is passionate about creating rich user interfaces and interactive applications using JavaScript.
  • Location
    London, UK.
  • Work
    Frontend 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.

CollapseExpand
 
thalisses profile image
Thalisses Jenn
Non Binary !01
  • Location
    São Paulo, BR
  • Joined

Very helpful this config of VS Code, thanks!

CollapseExpand
 
ehsansarshar profile image
Ehsan sarshar
  • Joined

what is the difference between x?.y?.z || 24 and x?.y?.z ?? 24

CollapseExpand
 
ismail9k profile image
Abdelrahman Ismail
👨‍💻 Tech Lead | 10+ yrs in Software Engineering🤖 Sharing pragmatic tips on AI & Development🌍 From 🇪🇬 based in 🇹🇷
  • Email
  • Location
    Istanbul, Turkey
  • Education
    Computer Engineering
  • Work
    Software Engineer & Tech Lead
  • Joined
• Edited on• Edited

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

CollapseExpand
 
decibel_dj profile image
Dhaval Patel
  • Joined

where can I find .babelrc & .eslintrc files ?
Inside node-modules folder, I can see lot of files with the same name.

CollapseExpand
 
brittanmcg profile image
Brittan McGinnis
  • Joined

They should be at your project's top level.

MyProject|_ .babelrc|_ .eslintrc
Enter fullscreen modeExit fullscreen mode

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

👨‍💻 Tech Lead | 10+ yrs in Software Engineering🤖 Sharing pragmatic tips on AI & Development🌍 From 🇪🇬 based in 🇹🇷
  • Location
    Istanbul, Turkey
  • Education
    Computer Engineering
  • Work
    Software Engineer & Tech Lead
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp