DEV Community

Discussion on: 10 Clean code examples (Javascript).

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️
const a = foo.x, b = foo.y;
const { ['x']: a, ['y']: b } = foo;

I don't know why anybody would ever prefer the second example; it's extremely cluttered and unreadable.


const elements = {};
['a', 'b', 'c', 'd'].forEach(item => elements = { 
  ...elements, 
  [item]: document.getElementById(item) 
});
const { a, b, c, d } = elements;

That code is an abomination. It borders on obfuscation. If you want to outsmart yourself and your coworkers, at least write it as

const [a, b, c, d] = ["a", "b", "c", "d"].map(id=>document.getElementById(id))
Enter fullscreen mode Exit fullscreen mode

but preferably, just assign the variables one by one.


foo && doSomething();

There's no real benefit to this other than to confuse non-js developers. If your goal is to write code that only the purest of JS disciples can understand, go ahead. But if you want to write code that others can read, use an if-statement.

if (foo) doSomething();
Enter fullscreen mode Exit fullscreen mode

const { ['log']: c } = console;
c("something");

Debugging is the one and only situation where being lazy about typing is acceptable. Generally speaking though, one-letter variables should be avoided.

Collapse
 
redbossrabbit profile image
Ibeh Ubachukwu

Thanks for the tips. We are all learning😁

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

We all at some point go through a phase where we want to use esoteric language features to write "smart" code, and it's also a phase we all eventually grow out of.

My recommendation is: prefer writing one or two extra lines of code if it helps to show the structure of the algorithm. Big-picture architectural decisions have a much larger impact on readability and how smart your code seems*.

* I don't remember ever seeing a snippet of clever code and being amazed for more than 5 seconds; but there's a few smart design-decisions that I still admire to this day for how much complexity they remove.

Thread Thread
 
padje profile image
Peter dJ

Devs sometimes forget that most extra lines of code have essentially no impact on execution speed... Whereas they can really help legibility.