DEV Community

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

Collapse
 
andrewbridge profile image
Andrew Bridge

There are some good tips here! I hadn't come across the numeric separators, and it's great to see a replaceAll method after years of having to reach for a regex for that simple task!

One thing I'd note is being careful with falsey checks, in #3 your Longhand version would allow any value other than those you've specified. The Shorthand version would also fail the value 0 and false. If you're working with numbers, that can cause tricky to find bugs later on.

The other bit may be more of a preference but nested ternary statements or function calls via a ternary (as in #8) are quite hard to read compared to the "long" alternative and that could make it far more susceptible to bugs and harder to find it when it comes up. I'd far prefer 5 clear lines of code and let my minifier convert it to a one liner before I push my code live!

Anyway, great list! Thanks!

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.

Collapse
 
flyingcrp profile image
flyingCrp

nice~
The code is used by the machine,and another function is to show it to people .
We have to make some trade-offs