DEV Community

Cover image for What in the IF is a ternary?

What in the IF is a ternary?

Matthew Carpenter on September 13, 2018

Being a "newb" to Javascript syntax can be a bit overwhelming at times. For starters, you can solve any single problem 10 different ways. Which mea...
Collapse
 
tux0r profile image
tux0r

If you have the choice between concise and obvious code, you should choose obvious code. Elegance involves debugability.

Collapse
 
itsasine profile image
ItsASine (Kayla)

It's worth noting that ternaries work in setting values not executing statements.

if(something) {
  doAThing();
} else {
  doAnotherThing();
}

can't be reduced to

something ? doAThing() : doAnotherThing();

Though I do think it reads easy (even nested) so long as what you're assigning is simple.

var thing = stuff ? 42 : 'thingy';

Having longer strings is where it gets to be cleaner to just write out the if-else.

Collapse
 
joelnet profile image
JavaScript Joel

It's worth noting that ternaries work in setting values not executing statements.

if(something) {
  doAThing();
} else {
  doAnotherThing();
}

can't be reduced to

something ? doAThing() : doAnotherThing();

There's nothing that would prevent a ternary from executing statements. That statement is perfectly valid JavaScript.

// VALID: You can also use a ternary to execute functions!
something ? doAThing() : doAnotherThing();
Collapse
 
itsasine profile image
ItsASine (Kayla)

Really? I never saw that as a valid option in IntelliJ within the Jasmine/ES5 realm :o Nice!

Collapse
 
offendingcommit profile image
Jonathan Irvin

I agree with @tux0r on this one. Ternary statements are awesome for showing off fancy JS skills, but in practicality, they're very hard on the eyes.

To add to the madness, you can chain ternary statements together ad nauseum. At that point, it's less about fanciness and more about "just because you can, doesn't mean you should."

To tux0r's point, if you're reading the code in your head as if condition, then expression, why not write it out as such?

Collapse
 
hugo__df profile image
Hugo Di Francesco

Since ternaries push you to use expressions, it makes your code less about control flow (if this, do that, else do something else) and more about "given this and that, send this value back".

It's very easy to write a lot of code in the if/else that should have been written as a set of functions acting one after the other to transform the data.

Of course if you've got small functions and aren't doing much within your if/else, it'll help long term maintainability.

Collapse
 
lucasmonstro profile image
Lucas Silva

console.log(ageRequirement); instead of console.log('ageRequirement');

Collapse
 
mcarpenter profile image
Matthew Carpenter • Edited

Thank you will update that shortly.

Collapse
 
lucasmonstro profile image
Lucas Silva

U're welcome mafriend! :)

Collapse
 
ben profile image
Ben Halpern

Thanks for a really concise writeup.