A beginner’s guide to optional chaining

question mark written on a wall
Photo by Matt Walsh on Unsplash

Hello there,

So, you’re probably wondering what optional chaining is and why it is even important. Well, you don’t have to worry no more. I also had my share of confusion when I had my first contact with it in a codebase that I was trying to work on. Now I know the nitty-gritty of how to use it, and I’d love to share it with you.

Before we continue, I would like to inform you that this is my first technical writing (ever) So let me know your thoughts in the comment section below.

Okay. Enough talk, let’s dive in

let us start with the formalities.

What is optional chaining (?. )

Optional chaining ?. lets you read the value of the property of an object that is within a chain without having you write a condition.

Okay, let me show what I mean. Imagine you have an object of customers which has a property location that also has a citysay you want to get the value of city but you’re not sure that location exists. Without optional chaining, you might do this

let customerCity = customer && customer.location && customer.location.city

Oh no! that’s too long! right?

well, all you have to do with optional chaining is

let customerCity = location.currentLocation?.city

if the location is undefined, instead of throwing a reference error, the customerCity becomes null Not only is this cool, shorter, and simpler, but it makes you feel like a senior developer.

Now, it doesn’t work for just objects, you can use the optional chaining for arrays and functions also.

obj?.[2]
obj.func(“arg”)?.value

Maybe you know this already but it wouldn’t hurt to remind you that Optional chaining cannot be used on the left side of an assignment. meaning you cannot do this.

let customer.location?.city = “Lagos”;

Optional chaining is supported in the latest CRA (create-react-app) version, but to enable it in an older version of react we’d have to use a babel plugin.

yarn add customize-cra react-app-rewired @babel/plugin-proposal-optional-chaining -D
OR
npm install customize-cra react-app-rewired @babel/plugin-proposal-optional-chaining

then, to enable you to override configuration, create a config-overrides.js file in the root of your folder and add the following code

const { useBabelRc, override } = require(‘customize-cra’);
module.exports = override(useBabelRc());

you can enable the plugin in the .babelrc file

{
“plugins”: [“@babel/plugin-proposal-optional-chaining”]
}

Okay, one last thing, we would have to modify the package.json file in the script section a little so it can run our config file and babel plugin, replace the script with the one below:

“scripts”: {
“start”: “react-app-rewired start”,
“build”: “react-app-rewired build”,
“test”: “react-app-rewired test — env=jsdom”
},

Okay, that’s it, we have successfully enabled optional chaining in the previous version of React.

I hope this explains why your colleague used ?. in their code. Let me know what you think in the comment section below.

--

--

--

I am a frontend developer, in love with SCSS and React

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Capturing browser console logs with cypress-terminal-report

How to check if the Object is empty?

How to check if an object is empty or not

DBeaver and Byte Order Mark

Creating a Leaderboard for a React/Rails Application

Bootstrap Session Timeout Example In Laravel

Bootstrap Session Timeout Modal Example

WebXR category with PlayCanvas

Bridging the Gap Between SSR and Client-State Persisted Data with next-persist

How to implement Material UI Data Grid in your Project — Part-II

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Elizabeth Lola

Elizabeth Lola

I am a frontend developer, in love with SCSS and React

More from Medium

Unidirectional and Bidirectional Data Flow — The Ultimate Front-End Interview Questions Guide Pt: 1

Handling Stale Closures and Accessing Latest State in React’s UseEffect.

When learning about react, how useful is it to know about react hooks and components?

Integrating Your New and Legacy React Applications with Asgardeo