DEV Community

Discussion on: 17 Javascript optimization tips to know in 2021 🚀

Collapse
 
jafuentest profile image
Juan A. Fuentest Torcat

+1 I would advise to not nest two or more ternary operations. Also avoid it entirely if it means you'll get a single like 100+ characters long, or 120 depending on preference. But more than that usually means your code will be hard to read

Collapse
 
blessinghirwa profile image
Blessing Hirwa

Long chained tenary operators are not good.

Collapse
 
hiasltiasl profile image
Matthias Perktold

When I have nested ternaries, I format them this way:

Ë‹Ë‹Ë‹javascript
let test2 = (x > 100) ? 'greater 100'
: (x < 50) ? 'less 50'
: 'between 50 and 100';
Ë‹Ë‹Ë‹

IMHO this reads quite nicely, since every condition is paired with the corresponding result, similar to a ˋswitchˋ block or an if-elseif-else chain.

Still, you shouldn‘t push it too far. When the conditions or value expressions get long, this becomes unreadable as well.

Thread Thread
 
andrewbridge profile image
Andrew Bridge • Edited

I agree, it reads nicely enough, but what's the benefit to this over:

let test2 = 'between 50 and 100';
if (x > 100) { test2 = 'greater 100'; }
else if (x < 50) { test2 = 'less 50'; }
Enter fullscreen mode Exit fullscreen mode

It's dealers choice with regard to using an else statement or default assignment as above and the formatting isn't my cup of tea, but it's still nevertheless the same statement on three lines. IMO, this is still way clearer and I don't see any downside to it.