DEV Community

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

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

3 2

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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (2)

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

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay