TIPS FOR CLEAN CODING IN JAVASCRIPT — PART1

Merve KILINC YILDIRIM
7 min readMay 14, 2024

--

Photo by https://dreamstudio.ai/

What is Clean Code?

“If you have to think about what a code block does for more than a minute, then this is not a clean code” :)

Of course, it is not so easy to decide if the code is clean or not clean. The fundamental principle of clean code is clarity and readability, ensuring that it’s easy to understand and maintain. In a project, writing a clean code is really important for a team’s efficiency. Because a developer in the team should spend his/her time to develop new features, not try to read and understand someone else’s source code.

In my opinion, writing clean code is a fundamental responsibility of each developer in a team because the colleagues should easily read, understand, and maintain each other’s code. For a more efficient and better development environment, this must be a common goal for the development team.

“Clean code always looks like it was written by someone who cares.” by Robert C. Martin

Yes, in a team, people should care each other, right:)

Of course, as a developer in an agile world, we always want to complete our tasks on time and end the sprint successfully (without any spillovers:). To do this, we SOMETIMES may have to do rapid development in order to finish our tasks immediately. And as a result, we may have quick code, not clean code. Because writing clean code takes time. You may need to go over your code multiple times. It is not easy to write the best code right at the start.

To write a clean code, you should always review and refactor your code.

It is not about the code is working or not. It’s about if the code is readable, understandable and maintainable.

The source code should follow some common best practices, should avoid big code blocks, complex nested codes and confusing naming.

Since clean coding is a very broad and important field, I would like to express my opinions on this subject in two parts. In Part1, I want to mention “Naming”, “Comments” and “Code Formating”. In Part2, I will talk about “Functions”, “Objects” and “Data Structures”.

Now, let’s take a closer look for the details of the best practices in JavaScript.

Naming

Good names helps us to understand the source code easily. Names should be meaningful and descriptive. With meaningful function, class or variable names, the reader does not need to go through your code and take a look at the details of it. While using distinctive names, we should also keep them short.

Now, let’s take a look at how we can name our variables, functions and classes.

First, we need to find the best nouns that describes the data the variable stores or the best verbs that describes the job the function performs or the best nouns that describes the object the class creates.

Next, we need to decide the name casing. In JavaScript, camelCase is the most commonly used naming convention for variables and functions and PascalCase is generally used for classes. Of course, you can always choose another casing, for the compatibility reasons, just try to use the same casing through the project.

In example code, you can see, class definition (f) is confusing and the method (d) is poorly named. The instances of the class f are created with non-descriptive names (fruit1 and fruit2).

// Unclear class definition
function f(n, c) {
this.n = n;
this.c = c;
this.d = function() {
console.log('This ' + this.n + ' is ' + this.c + '.'); }
}

// Create instances of the unclear class
let fruit1 = new f('apple', 'red');
let fruit2 = new f('banana', 'yellow');

// Call method on instances
fruit1.d(); fruit2.d();

To make it more clear, we can start with good naming. In the source code below, you can see the clear version of our example code.

// Class representing a Fruit 
class Fruit {
constructor(name, color) {
this.name = name;
this.color = color;
}

// Method to display information about the fruit
displayInfo() {
console.log(This ${this.name} is ${this.color}.);
}
}

// Create instances of the Fruit class
let apple = new Fruit('apple', 'red');
let banana = new Fruit('banana', 'yellow');

// Display information about the fruits
apple.displayInfo();
banana.displayInfo();

We updated the class name as Fruit. We gave proper names for (name and color) the properties and the method (displayInfo) of the class. We used PascalCase for class name and camelCase for the function name. Finally, meaningful variable names (apple and banana) improved source code understanding.

Comments

While the comments are needed to increase the readability and understandability, they may also add unnecessary complexity to the source code. Therefore, while using comments, we should be careful. We should not use misleading and redundant comments to not confuse the reader. We should also avoid leaving commented-out code in our project.

We can use comments to explain a code piece that is not self-explanatory, eg. regexes. And of course, we can use “TODO” comments as reminders for the future tasks.

In the example, you can see bad examples of comments. As you can see, the reader does not understand what the regex does when he/she reads the code. Also, the comment “Save the price” misleads the user. Because the function name “calculateTotalPrice” and the comment are not consistent.

On the other hand, the comment “Sum price and taxAmount” is redundant for the reader since it is obvious what code below does.

Note that, it is a good practice to remove the commented-out code and add TODO key word for the future work.

const myRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

// Save the price
const calculateTotalPrice = (price, taxRate, email) => {
const taxAmount = price * (taxRate / 100);

//Sum price and taxAmount
const totalPrice = price + taxAmount;

// Old implementation (don't use)
// const oldFunc = () => {
// const total_price = myCalculation(x1, x2, x3);
// return total_price;
// };
if(myRegex.test(email)){
//for now, not sends email
sendEmail();
}
​ return totalPrice;
};

In the source code below, you can see the clean version of our example code.

// Regex pattern to match a valid email address
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

// Calculate the total price including tax
const calculateTotalPrice = (price, taxRate, email) => {
const taxAmount = price * (taxRate / 100);
const totalPrice = price + taxAmount;

if(emailRegex.test(email)){
//TODO not sends email, implement sendEmail function
sendEmail();
}

​ return totalPrice;
};

Code Formatting

The source code should be well-formatted. The readers should easily read it, not need to go forward or backward. Here are some tips for better formatting:

  • We should split our source code with different concepts into multiple files. For example, we can put our functions for file processing to one file and functions for database operations to another file.
  • We should keep the similar and dependent functions closed to each other.
  • We should use blank lines between functions. We should care about the compatibility of indentation and line breaks .
  • We should keep the lines short and not use horizontal alignment.

It is not easy to format the source code manually, it takes time and error prone. So we can use code formatting tools. There are a set of online tools and code editor plugins. Here are some examples:

  • JavaScript Beautifier: You can beautify JavaScript, JSON, React.js, HTML, CSS, SCSS and SAAS.
  • Code Beautify: It is an online code formatter that you can paste, type your source code or upload the source code file.
  • Prettier.io: It is a plugin supports many languages and integrated with most editors such as Atom, VSCode, WebStorm and more.

Here you can see an example of a bad formatted JS code.

var productName="apple";var quantity=5;var totalPrice;

function calculateTotalPrice(productName, quantity) {
var pricePerUnit=getProductPrice(productName);var totalPrice=pricePerUnit*quantity;return totalPrice;}
function getProductPrice(productName) {
if(productName==="apple"){return 1.50;}else if(productName==="orange"){return 2.00;}else if(productName==="banana"){return 0.75;}else{console.log("Product not found!");return null;}}

totalPrice=calculateTotalPrice(productName,quantity);console.log("Total price for "+quantity+" "+productName+"(s): $"+totalPrice.toFixed(2));

According to the tips that we mentioned above, you can see the beautified version of our example code. It’s obvious that how readable a well-formatted source code is.

function getProductPrice(productName) {
if (productName === "apple") {
return 1.50;
} else if (productName === "orange") {
return 2.00;
} else if (productName === "banana") {
return 0.75;
} else {
console.log("Product not found!");
return null;
}
}

function calculateTotalPrice(productName, quantity) {
var pricePerUnit = getProductPrice(productName);
var totalPrice = pricePerUnit * quantity;
return totalPrice;
}

var productName = "apple";
var quantity = 5;
var totalPrice = calculateTotalPrice(productName, quantity);
console.log("Total price for " + quantity + " " + productName + "(s): $" + totalPrice.toFixed(2));

Conclusion

Writing clean code is not an easy task, it is not cheap, that’s the truth. But by writing clean, well-structured code, you’ll build robust, maintainable, readable, understandable software that meets both current and future needs. Isn’t it worth it?:)

These are my insights about clean coding and my main references are “Clean Codewritten by Robert C Martin and “Clean Code” on Udemy by Maximilian Schwarzmüller. I highly recommend these two resources to anyone. Hope you’ll enjoy.

Stay tune for Part2:)

--

--