DEV Community

Discussion on: Optional Chaining in Javascript

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 Author

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 :)