How to write clean javascript Code

--

So the past week I have been learning about clean code and good practice while writing javascript code and wanted to share some of my learnings with you guys this is titled clean javascript code but I think most of the stuff is basic and generic and can be implemented in any programming language.

Let's start:

1. Naming Conventions.

  • Use better naming for the variables and constants.
  • Example we have to declare two times of a train that is Arrival and departure time.
  • Now in this scenario many people will use
Let time1 = new Date(2020,2,2)Let time2 = new Date(2020,2,2
  • These naming can be improved immensely and the reader can understand better by declaring the variable more wisely like this :
Let arrivalTime = new Date(2020,2,2)Let departureTime = new Date(2020,2,2
  • Another example of declaring the user object with details.
const obj = {
username: "Pratik Tiwari",
rollNo: 22
  • This is not the best name for this object.
const user = {
username: "Pratik Tiwari",
rollNo: 22
}
  • Here user makes more sense rather than an obj naming.
  • Another example of JSON objects is. Suppose..
const car = {
carName: "Pratik Tiwari",
carModel: x02
carPrice: 282882
}
  • So instead of using car all-time use just its features as the name of the object is a car so the reader will understand that we are talking about car
const car = {
name: "Pratik Tiwari",
model: x02
price: 282882
}

2. Functions Conventions.

  • Try not to increase the arguments of your function to be more than 2. If its more than 2 you should look into changing the structure of the data
  • Example:
function saveDetails(name, model, price, color) {
// logic to save
}
  • Rather than this we can define an object and take that as an argument and deconstruct it if want.
const car = {
name: "Pratik Tiwari",
model: x02,
price: 282882,
color: red
}
function saveDetails(car) {
// logic to save
}
  • Write unit-testable code. Don’t cramp up the logic to a single function rather break your logic into different functions.
function emailActiveClients(clients) {
clients.map(client => {
const clientRecord = DB.lookip()
if(clientRecord.isActive) {
sendEmail(clientRecord.email);
}
})
}
  • This should be broken like this
function emailClient(clients) {
clients.filter(isActiveClient).forEach(email);
}
function isActiveClient(client) {
const clientRecord = DB.lookip(client);
return clientRecord.isActive;
}
  • The function name itself should tell what the function does. Avoid writing duplicate code.
  • Take for example this function:
function showDeveloperList(developers) {
developers.forEach((developer) => {
const expectSalary = developer.calculateExpectedSalary();
const experience = developer.getExperience();
const githubLink = developer.getGithubLink();
const data = {
expectedSalary,
experience,
githubLink,
};
render(data);
});
}
function showManagerList(managers) {
managers.forEach((manager) => {
const expectSalary = manager.calculateExpectedSalary();
const experience = manager.getExperience();
const githubLink = manager.getMBAProjects();
const data = {
expectedSalary,
experience,
portfolio,
};
render(data);
});
  • So here we see two different functions which have two different purposes and justify themselves very perfectly. but here we see some things in the function are the same and hence can we combine them into one different function to avoid repeating our self and to reuse code.
  • The only change in both the function is in developer we are getting GitHub link and in manager, we are getting Portfolio link and hence we handle that and we can reuse the rest code very easily.
function showEmployeeList(employees) {
employees.forEach((employee) => {
const expectSalary = employee.calculateExpectedSalary();
const experience = employee.getExperience();
const data = {
expectedSalary,
experience,
};
switch (employee.type) {
case "manager":
data.portfolio = employee.getMBAProjects();
break;
case "developer":
data.github = employee.getGithubLink();
break;
}
render(data);
});
}

3. Small and Unit testable functions.

  • Suppose we have a scenario where we have to perform operations on different data we can do it in the same function but having that differentiated in different function makes it visibly appealing and also unit-testable:
var items = [
{
name: 'RAM',
price: 77.99,
bought: true
},
{
name: 'CPU',
price: 177.99,
bought: false
},
{
name: 'Mouse',
price: 7.99,
bought: false
},
{
name: 'Hard Drive',
price: 77.99,
bought: false
},
{
name: 'Keyboard',
price: 37.99,
bought: true
}
]
  • This how we should write the function for our scenario:
function generateIds(item){
return items.map((i, index) => {
i.id = index + 1;
return i;
})
}
function getTotalCost(items){
return items.filter(i => i.bought);
}
function getBoughtItems(items){
return items.filter(i => i.bought);
}
functionCalculateCost(items){
let cost = 0;
items.forEach(i => {
cost = cost + i.price;
})
return cost;
}
function getTotalCost(items){
const itemsWithIds = generateIds(items);
const boughtItems = getBoughtItems(itemsWithIds);
return calculateCost(boughtItems);
}

Avoid side effects

  • what usually a lot of developers do is suppose when we have an array and we need to add a value to it and return the newly added array we simply push the element to the array which is not the best option instead what we should do is we should create a new copy of the array and return the new array with the new value-added. let's see it visibly in the example below.
const addItemToCart = (cart, item) => {
cart.push({item, date: Date.now()});
}
const addItemToCart = (cart, item) => {
return [...cart, {item, date: Date.now()}]
}

Declarative code and Functional Programming.

  • Avoid writing imperative code. i.e when you start writing simply for loops everywhere use more functional programming.
  • How this effect and looks lets see by an example:
// imperative style
var totalOutput = 0;
for (let i = 0; i < programmerOutput.length; i++) {
totalOutput += programmerOutput[i].linesOfCode;
}
// Declarative style
const totalOutput = programmerOutput.reduce((lines, output) => {
return lines + output.linesOfCode;
}, 0);
const newResult = programmerOutput.filter(i => i.linesOfCode >= 1000).map(i => {
return {
...i, coolCoder = true
}
})

So these were some of the stuff that I really think is very basic and important while writing clean code.

Share if you liked it :)

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Pratik Tiwari
Pratik Tiwari

Written by Pratik Tiwari

Decentralized & Distributed systems • AI • Web3 • Backend and Frontend systems https://tiwaripratik.com/

No responses yet

Write a response