DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 970,177 amazing developers

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

Create account Log in
Cover image for How to Make your If Statements more readable by using this ES2020 Feature
Carsten Behrens
Carsten Behrens

Posted on • Updated on • Originally published at carstenbehrens.com

How to Make your If Statements more readable by using this ES2020 Feature

Have you ever written an if-statement like this?

// The object we are working with
const car = {
  make: {
    name: "bmw",
    founded: 1916,
    country: "germany"
  }
}

if (car && car.make && car.make.name && car.make.name === "bmw") {
  // Do something.
}
Enter fullscreen mode Exit fullscreen mode

In JavaScript, we often check if each property exists.
We do this because we don't want to run into errors.

The only problem:

  • It's ugly
  • It's harder to read than it needs to be
  • Noise-to-Signal Ratio is high

THE BETTER WAY

Thanks to optional chaining which is part of ES2020, you can now do this:

// The object we are working with
const car = {
  make: {
    name: "bmw",
    founded: 1916,
    country: "germany"
  }
}

if (car?.make?.name === "bmw") {
  // Do something.
}
Enter fullscreen mode Exit fullscreen mode
  • Beautiful
  • Easier to read
  • Noise-to-Signal Ratio is low

In my opinion, it's the best way to check if a property exists in your if statements.

Top comments (2)

Collapse
 
withshubh profile image
Shubhendra Singh Chauhan • Edited on

Good one! πŸ‘

We at DeepSource are also helping developers worldwide in shipping good code.
Recently we also published a blog about JavaScript best practices, Do take a look and share your thoughts. 😊

Collapse
 
xeoto profile image
xeOTO

Good one! πŸ‘

Visualizing Promises and Async/Await 🀯

async await

☝️ Check out this all-time classic DEV post