DEV Community

Discussion on: 10 Clean code examples (Javascript).

Collapse
 
wialy profile image
Alex Ilchenko • Edited

shortcleanreadable

2 Instead of

a = { [c > d ? 'foo' : 'bar']: 'apple' };
Enter fullscreen mode Exit fullscreen mode

it's better to split it into couple lines

const key = c > d ? 'foo' : 'bar';
const a = { [key]: 'apple' };
Enter fullscreen mode Exit fullscreen mode

4 might be even cleaner

const { x: a, y: b } = foo;
Enter fullscreen mode Exit fullscreen mode

6 seems overcomplicated, maybe something like

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

7 questionable, I'd say if construction is easier to understand, especially for juniors joining the project

8 use ?? instead of || - that way you'll not override 0 value

9 less known JS feature - you may use underscore to divide long numbers

const a = 1_000_000;
console.log(a); // 1000000
Enter fullscreen mode Exit fullscreen mode

bonus just use a debugger or create an IDE snippet.

Collapse
 
sergei profile image
Sergei Sarkisian • Edited

So, if initially a has several properties

let a = { foo: 'some', bar: 'example' };
Enter fullscreen mode Exit fullscreen mode

Then after

c > d ? a.foo = 'apple' : a.bar = 'apple';
Enter fullscreen mode Exit fullscreen mode

a will have same amount of properties.
But after

a = { [c > d ? 'foo' : 'bar']: 'apple' };
Enter fullscreen mode Exit fullscreen mode

It will hav only 1 property. It's not even the same!