Better if statement w/ ternary operator ? : πŸ’»

thomasaudo - Feb 5 '19 - - Dev Community

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 πŸ˜‡

. . .
Terabox Video Player