Write Cleaner Code in JavaScript #4 Comments

The Atypical Developer
2 min readOct 15, 2022

--

This is the third part of the clean code series. If you wish to start from the beginning just click here!

Comment stuff code only when necessary

Clean code is readable and usually does not require us to add any extra comments. So only comment things that have business logic complexity. This will help keep your codebase clean and easy to understand.

// Don't ❌function hashIt(data) {
// The hash
let hash = 0;

// Length of string
const length = data.length;

// Loop through every character in data
for (let i = 0; i < length; i++) {
// Get character code.
const char = data.charCodeAt(i);
// Make the hash
hash = (hash << 5) - hash + char;
// Convert to 32-bit integer
hash &= hash;
}
}
// Do ✅function hashIt(data) {
let hash = 0;
const length = data.length;

for (let i = 0; i < length; i++) {
const char = data.charCodeAt(i);
hash = (hash << 5) - hash + char;

// Convert to 32-bit integer
hash &= hash;
}
}

Don’t commit commented out code

// Don't ❌doSomething();
// doSomethingElse();
// doSomethingOld();
// Do ✅doSomething();

Don’t have journal comments

Use git log to get history. There’s no need for dead or journal code in your codebase.

// Don't ❌/**
* 2022-09-10: Removed conditions as they were not needed
* 2021-10-01: Added conditions
* 2020-03-03: Fixed NaN values issue
* 2020-02-14: Added multiply values function
*/
function multiplyValues(a, b) {
return a * b;
}
// Do ✅function multiplyValues(a, b) {
return a *b;
}

Avoid positional markers

This will help you understand the code better and make it easier to work with.

// Don't ❌////////////////////////////////////////////////////////////////////
// Initial Car Object
////////////////////////////////////////////////////////////////////
car = {
colour: "red",
productionYear: 2022
};

////////////////////////////////////////////////////////////////////
// Update Car Function
////////////////////////////////////////////////////////////////////
const updateCar = () => {
// ...
};
// Do ✅car = {
colour: "red",
productionYear: 2022
};

const updateCar = () => {
// ...
};

This is the end of the series. If you liked it, follow my stories for more!

--

--

No responses yet