DEV Community

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.

Discussion (2)

Collapse
withshubh profile image
Shubhendra Singh Chauhan • Edited

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! 👏