DEV Community

Dhilip kumar
Dhilip kumar

Posted on

Optional Chaining in Javascript

What if I tell you that the following snippet is Possible in javascript?


const hasWorld = response && response.data && response.data.msg && response.data.msg.includes('world');

const hasWorld = response?.data?.msg?.includes('world');

This way of checking the property of an object known as Optional Chaining.

This is currently in Stage 3 tc39, however with babel we will be able to use it in our code right now by adding the following plugin @babel/plugin-proposal-optional-chaining to your config file for babel v7+.

Below is the Transpiled Babel Code Example with Optional Chaining.

Transpiled code Example

Top comments (6)

Collapse
 
kenbellows profile image
Ken Bellows

You can actually take your code one step further:

const hasWorld = response?.data?.msg?.includes('world')

If msg is undefined, .includes() will never be called, and hasWorld will be undefined! One of my most awaited features

Collapse
 
dhilipkmr profile image
Dhilip kumar • Edited

Ohh yes thank you. I'll edit the snippet

Collapse
 
ivanalejandro0 profile image
Ivan Alejandro

Another alternative to:

const hasWorld = response && response.data && response.data.msg && response.data.msg.includes('world');

that you can use, if you don't want or can't to go with optional chaining.

let hasWorld = false;
try {
  hasWorld = response.data.msg.includes('world');
} catch (ignoreThisError) {
  // something went wrong, we don't care exactly why,
  // the string we look for is not there
}

If you're interested, I wrote some thoughts around this on dev.to/ivanalejandro0/simplify-nes...

Collapse
 
dhilipkmr profile image
Dhilip kumar

Try catch for every prop check in my cod would reduce its readability for sure. So, I personally would prefer the former. But yes it is an alternative approach

Collapse
 
ivanalejandro0 profile image
Ivan Alejandro

Yeah, I think that for this and many other things one of the most important things is what's easier to work with for you and your team :)

Collapse
 
dotorimook profile image
dotorimook

It sounds good. Is it able to apply @babel/plugin-proposal-optional-chaining to typescript CRA project? I tried to using the plugin with react-app-rewired and customize-cra, but it gets errors.