DEV Community

Cover image for Better if statement w/ ternary operator ? : 💻
thomasaudo
thomasaudo

Posted on

Better if statement w/ ternary operator ? : 💻

The if operator is a mainstay of computer programming, we use it everywhere.

Sometimes we need to test a value to then, execute some simple code:


if (a === b) {
    console.log('true');
} else {
    console.log('false');
}

This syntax is really clear and simple to use, but it takes a lot of place.

In a large-scale program, it can reduce the visibility and comprehension of the whole.

For a simple case like this, it's often more simple to use the ternary operator.

Syntax

(condition) ? (operation A) : (operation B)

This operator is very useful but often unknown or misunderstood by programmers.

Details:
- condition, the condition
- operation A, the action to execute if the condition returns true
- operation B, the action to execute if the condition is false, concretely an else

Example

Here is a simple example in javascript :

// If the age >= 18, then the adult variable takes the value true, otherwise, it's taking the value 
//false

age >= 18 ? adult = true : adult = false

// With a basic if statement

if (age >= 18 ) {
    adult = true
} else {
    adult = false
}

Way simpler no?

Another example: a function which returns the GCD of a and b.
However it's not the best example at all.

Indeed, it's not easy to read, a normal if statement will be better in this case.

function gcd(a, b) {

    return ( (a%b) === 0 ?  b : gcd(b, a%b) )

}


Conclusion

To conclude, this notation is really helpful and help us increase our productivity.
However, it has to be used in really simple cases.

For complex statements or operations, the if / else notation is still the best way!

Thanks for reading me 😇

Top comments (4)

Collapse
 
bezo97 profile image
Zotya Docs

If we're really going for simplicity, in this particular case you can just say

adult = (age>=18)

since the A and B operations just give back the result of the condition.
Here's one example that better demonstrates the case:

result = (age>=18 ? "adult" : "young")

Cheers!

Collapse
 
link2twenty profile image
Andrew Bone

You don't need the brackets either 🙂

Collapse
 
alainvanhout profile image
Alain Van Hout • Edited

A great many people mistake a decrease in number of characters for an increase in clarity. Or to say it in another way: dense isn't the same as concise.

Collapse
 
thomasaudo profile image
thomasaudo • Edited

Yes as I said in the conclusion, this syntax isn't adapted in all case, only in really simple one