DEV Community

Cover image for IF nothing ELSE, ternary...
Matthew Palmer
Matthew Palmer

Posted on

IF nothing ELSE, ternary...

Introduction

There's a little somethin' somethin' I've seen in other projects. The overuse of IF ELSE statements. Or should I say the improper use of them. The inefficient, ugly use of them. Let's talk about that.

The Ternary Operator

This is an amazing tool. Not only does it execute conditionals, it offers a clean code solution to an otherwise line greedy block of code. Take a look:

if(100 === +"100") {
    console.log("YES! WE DID IT! 100%");
} else {
    console.log("YOU BATHE IN LIES!");
}
Enter fullscreen mode Exit fullscreen mode

This isn't too bad, but it is definitely taking up way too many lines. Try this instead:

100 === +"100" ? console.log("YES! WE DID IT! 100%") : console.log("YOU BATHE IN LIES!")
Enter fullscreen mode Exit fullscreen mode

We went from 5 lines of code down to one! Confused? Let's break it down in a simple manner.

conditionIsTrue ? doThisIfTrue : doThisIfFalse
Enter fullscreen mode Exit fullscreen mode

It is almost the same as an IF ELSE statement, but know when you can use it and when you can't. Ternary operators are only meant to replace IF ELSE statements that only accept a single line response.

Example:

if(condition) {
   performThisAction();
   AaaandThenDoThisAction();
} else {
   doSomeOtherAction();
}
Enter fullscreen mode Exit fullscreen mode

This would not work with ternary.... This is because the if statement takes two actions when one condition is true. A ternary operator can only perform one action dependent on whether the given condition is true or not. There is a time and place for both the if statement and the ternary operator. Proper use of them is highly dependent on understand how they work, when and why we use them.

Conclusion

JavaScript has many useful tools, but there's an old saying you more than likely have heard before.... "with great power comes great responsibility". Code smarter, not harder. If nothing else, write code that is kind to others. If it takes up too much room and is unreadable, it's not very kind!

Happy Tuesday!

Top comments (1)

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

Then, prettier kicks in. It becomes 3 lines.