DEV Community

Cover image for 10 Clean code examples (Javascript).
Ibeh Ubachukwu
Ibeh Ubachukwu

Posted on • Edited on

10 Clean code examples (Javascript).

1. Assigning a value to the same thing conditionally using ternary operators.

  
a > b ? foo = 'apple' : foo = 'ball'; 

✔️  
foo = a > b ? 'apple' : 'ball';
Enter fullscreen mode Exit fullscreen mode

2. Assigning the same value to a specific object property conditionally.

  
c > d ? a.foo = 'apple' : a.bar = 'apple';

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

3. Exporting multiple variables

 
export const foo;
export const bar;
export const kip;

✔️ 
export const foo, bar, kip;
Enter fullscreen mode Exit fullscreen mode

4. Declaring and assigning variables from object properties.

  
const a = foo.x, b = foo.y;

✔️
const { ['x']: a, ['y']: b } = foo;
Enter fullscreen mode Exit fullscreen mode

5. Declaring and assigning variables from array indexes.

  
let a = foo[0], b = foo[1];

✔️
let [a, b] = foo;
Enter fullscreen mode Exit fullscreen mode

6. Getting multiple elements from the DOM.

  
const a = document.getElementById('a'),
b = document.getElementById('b'),
c = document.getElementById('c');
d = document.getElementById('d');

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

/*
For this to work your elements ID's must be 
able to be valid Javascript variable names
and the names of the variables in which you store
your elements have to match with that elements' ID.
This is good for naming consistency & accesibility.
*/
Enter fullscreen mode Exit fullscreen mode

7. Use logical operators for simple conditionals.

  
if (foo) {
  doSomething();
}

✔️
foo && doSomething();
Enter fullscreen mode Exit fullscreen mode

8. Passing parameters conditionally.

  
if(!foo){
  foo = 'apple';
}
bar(foo, kip);

✔️
bar(foo || 'apple', kip);
Enter fullscreen mode Exit fullscreen mode

9. Dealing with lots of 0`s.

`

  
const SALARY = 150000000,
TAX = 15000000;

✔️
const SALARY = 15e7,
TAX = 15e6;
Enter fullscreen mode Exit fullscreen mode


``

10. Assigning the same thing to multiple variables.

``

  
a = d;
b = d;
c = d;

✔️
a = b = c = d;
Enter fullscreen mode Exit fullscreen mode


``

Bonus⭐ (A deugging tip)

Debugging with console.log() can be a pain having to write it
over and over again. You can shorten it by object destructuring
assignment.

``

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


``

Now Instead of having to write out console.log()
you can just write c() which is easier to write for
faster debugging.

Thanks for reading!🎉.

View my github

Oldest comments (70)

Collapse
 
_genjudev profile image
Larson • Edited

Like it.

6 could be better by just creating the object directly. Its faster and better to read.

Also dont to 10. If u coding like that there is a good chance u get race conditions. Also by working with objects:

let a = b = c = {"a":"b"}
a.a = "p"

console.log(c)
// { a: "p" }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
redbossrabbit profile image
Ibeh Ubachukwu

Thanks! Learning never stops.

Collapse
 
jamesthomson profile image
James Thomson

Myself, I would call most of these "less code" examples, not necessarily "clean code". Imo, clean code is legible code. A lot of these examples require the developer more mental fatigue. Some of these I do, but others I definitely avoid, especially #10.

Collapse
 
redbossrabbit profile image
Ibeh Ubachukwu

Thank you. I should probably work on my article title naming 😅

Collapse
 
khangnd profile image
Khang

Considering all the feedback, I do believe this article should be renamed to avoid misleading to learners, seriously.

Thread Thread
 
redbossrabbit profile image
Ibeh Ubachukwu

Nah..😄. I think the feedback will help people understand better what clean code is and isn't.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

I don't think #10 is all that bad. It's a bit confusing to figure out which variable gets assigned to the others, but that's easily figured out to be the right-most variable. Logically speaking, it does make sense: all those variables end up being equal to each other.

Collapse
 
jamesthomson profile image
James Thomson

It's a bit confusing to figure out which variable gets assigned to the others

That’s exactly my point. It causes mental fatigue. If you have to stop and think about how something as simple as this is constructed then it reduces the legibility of the code. It’s not that hard to figure out, but it still isn’t absolutely clear and imo it’s unnecessary.

Thread Thread
 
mellen profile image
Matt Ellen-Tsivintzeli

10 could be really bad in a language like c++ with operator overloading. But, yeah, the "incorrect" version is much clearer, regardless.

Thread Thread
 
dasdaniel profile image
Daniel P 🇨🇦

what about const [a, b, c] = [d, d, d]; ?

brent approves

Collapse
 
weironiottan profile image
Christian Gabrielsson

Agreed with you, Code Readability should trump trying to shave off lines of code.

Collapse
 
dasdaniel profile image
Daniel P 🇨🇦

☝💯
A bunch of these seem more clever than clean.

I consider the #1 priority of the code to easily communicate what is happening.
consider these two examples

const a = foo.x, b = foo.y;

✔️ const { ['x']: a, ['y']: b } = foo;

I don't know if I'm "over-indexing" on my experience here, but I'd say the "incorrect" example is easier to comprehend.

Collapse
 
jamesthomson profile image
James Thomson

The "incorrect" version is definitely less cognitive load. I also prefer individual const definitions as well for that extra level of legibility when scanning the code.

Collapse
 
charleshimmer profile image
Charles Himmer • Edited

#4 could also be written much simpler like this:
const { x: a, y: b } = foo;

Collapse
 
ishwarm81238332 profile image
Ishwar More

But there is no b. keys are different and value is same (here a).

const { ['x']: a, ['y']: a } = foo; will not be possible

Thread Thread
 
jamesthomson profile image
James Thomson

It's re-assigning the value. ['y']: b assigns the value of y to b so you can now access it as b.

Collapse
 
valeriavg profile image
Valeria

When dealing with lots of zeros it's also possible to use underscore to separate ranks:

const num= 10_000_000;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
redbossrabbit profile image
Ibeh Ubachukwu

Thanks. Finally a responsible dev community! 😄

Collapse
 
redbossrabbit profile image
Ibeh Ubachukwu

I meant to say responsive*. But I guess responsible works fine too. Autocorrect issues😤

Collapse
 
valeriavg profile image
Valeria

Haha, no worries!)

Collapse
 
e11y0t profile image
Elliot Wong

Woah didn't know this until now! This will defo help with code readability, thanks :)

Collapse
 
yaireo profile image
Yair Even Or • Edited

Number 4...?! what is going on there.. it should be as follows:

var foo = {x:1, y:2}
var {x:a, y:b} = foo
console.log(a,b)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
redbossrabbit profile image
Ibeh Ubachukwu

I guess that works too! 😅

Collapse
 
jivkojelev91 profile image
JivkoJelev91

Everything is fine, except 6. There is no need to create a new object, new array, loop over them and so on, this is neither clean, neither fast.

Collapse
 
redbossrabbit profile image
Ibeh Ubachukwu

Thanks!. It thought it would be helpful when you have to get alot of elements from the DOM. I guess its more of 'less' code than 'clean' code 😄

Collapse
 
thefern profile image
Fernando B 🚀 • Edited

Yup he had me sold on most, except 6 and 10. One note on 6 might be a good case, if you're looping through a known array, but for this specific example I don't think is worth the hassle.

Collapse
 
ouzsrcm profile image
ouzsrcm

thanks a lot!

Collapse
 
redbossrabbit profile image
Ibeh Ubachukwu • Edited

You are welcome. Just be sure to read the comments. There are alot of helpful tips and corrections there 😄👍

Collapse
 
kvetoslavnovak profile image
kvetoslavnovak

Thank you!
BUT I was told by all my teachers:
"NEVER show incorrect examples to students or highlight possible mistakes!"
ALWAYS teach only correct examples.

Collapse
 
redbossrabbit profile image
Ibeh Ubachukwu

I'm not perfect 😄, No one is. I didn't intentionally make incorrect examples. That's why this is a community for learning and why there is a comment section. I can be corrected. A student that truly wants to learn and grow would research further after getting information from anywhere.

Collapse
 
sirmoustache profile image
SirMoustache

I think the lack of explanation for each case makes this kind of article harmful for new developers. Also adding an explanation will allow the author to double-check these tips.

Collapse
 
redbossrabbit profile image
Ibeh Ubachukwu

I understand that but further research has to be made by a developer when getting information from any kind of article i.e if the developer truly wants to grow. This kind of article is just to get the gears going 😁 hence the lack of explanation.

Collapse
 
sirmoustache profile image
SirMoustache

Well, yes. But also it's the author's responsibility to explain what he is suggesting. If you claim something - you need to provide prooves fou your words.

Thread Thread
 
redbossrabbit profile image
Ibeh Ubachukwu

It's good to leave room for imagination🌈🌠🌝

Collapse
 
jankapunkt profile image
Jan Küster 🔥 • Edited

I think clean code is still a very debatable topic. To me, personally, clean code is code with improved readability or improved contextual information:

Example:

const g  = 9.81 // unclear
const GRAVITY_OF_EARTH = 9.81 // clear
Enter fullscreen mode Exit fullscreen mode

Same goes for preparing structures for commenting code:

hard to read

if (condition) {
  // long block comments about 
  // what this branch actually does
  ...
} else {
  // long block comments about 
  // what this branch actually does
  ...
}
Enter fullscreen mode Exit fullscreen mode

easier to read:

// long block comments about 
// what this branch actually does

if (condition) {
  ...
}

// long block comments about 
// what this branch actually does

else {
  ...
}
Enter fullscreen mode Exit fullscreen mode

Some comments may only be visible to logged-in visitors. Sign in to view all comments.