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.
}
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.
}
- 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)
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. 😊
Good one! 👏