DEV Community

Discussion on: 10 Clean code examples (Javascript).

Collapse
 
andrewbridge profile image
Andrew Bridge • Edited

I think these are great easter eggs one might use for code golf. The fact Javascript can do these things is probably worthwhile knowing to be more comfortable with the language.

However most of these are trick shot one liners that I'd probably point out as being too fiddly if I saw them in a code review.

Snippet 2 took me long enough to understand what was going on that I'd probably just flag it without going any further to even check if the logic was correct. However the assignment within the ternary (the example of "wrong" code) is also the type of thing I'd consider overly complicated. A nice, clear if statement would've been fine.

Snippet 8 is another where I would far prefer to read the first, "wrong" example and would understand it straight away.

Snippet 6 has been mentioned several times, but the "correct" example is not only more complicated, but actually far less efficient. The "wrong" example does 4 simple assignments, the Javascript engine will be able to optimise these 4 lines really easily. Your "correct" code:

  • creates a new object
  • creates a new array object
  • iterates over that new array with a new function
  • spreads and reassigns the object every time into yet another new object
  • finally dumps the object, assigning the values to the local scope

The Javascript engine uses more CPU cycles running it and has to allocate more memory to store all that extra state, and even worse, the garbage collector now has a whole mess to clean up afterwards that doesn't get used ever again.

Just to balance things out, #7, #9 and your bonus tip are genuinely useful shortcuts, that make things easier to read and work with, and I use all three in everyday development. Great things to point out!

I think the main takeaway is that clever tricks are fun to work out and discover, but they're rarely better than the simplest possible code. Also "Clean code" !== shortest code. In fact, it's often better to have 5 lines instead of one if it makes it clearer what's going on. After all, if I want my code smaller and shorter, I'll put it through a minifier and an uglifier before I ship it to production, and let the computers deal with the one liners!

Collapse
 
redbossrabbit profile image
Ibeh Ubachukwu

More knowledge! 🧠💪