Education

5 ways to improve your frontend code with JavaScript refactoring

logo

DhiWise

September 28, 2022
image
Author
logo

DhiWise

{
September 28, 2022
}

It's nearly impossible to write a perfect code all at once, but it can be refactored to improve the code quality. In this article, we will discuss what is code refactoring and the different approaches to refactoring JavaScript code.

So let's get started!

What is code refactoring?

Code refactoring is the process of restructuring existing software code without changing its external behavior. Code refactoring helps to improve the design structure and implementation while preserving the core functionality. 

It is beneficial for:

  1. Improving the code readability
  2. Reducing code complexity
  3. Improves code testability and maintainability
  4. Software scalability
  5. Increases software performance 

In JavaScript, refactoring can be applied to different levels i.e classes, methods, modules, and services (we can call it components). The process mostly involves splitting the code into smaller chunks so that each of the components should only have one responsibility (Single responsibility principle). 

Refactoring JavaScript code enables developers to work more efficiently while debugging, maintaining, and scaling up code for new functionality. 

Let’s look into some of the refactoring ideas to improve your software code quality.

JavaScript Refactoring: 5 ways to improve your code quality with refactoring

1. Follow JavaScript standards for refactoring

Like any other programming language JavaScript has its own set of standards to write better code. Following these coding standards helps you to improve the code quality. 

Here are some commonly used standards in Javascript programming.

1. Naming convention
Arrays

Arrays contain a list of items, therefore, it's good practice to append “s” at the end of the array name. So whenever developers read a variable name they immediately understand that it must be an array.

For example: 

const cars = ["Saab", "Volvo", "BMW"];
Booleans

For naming boolean variables it's better to use natural language.

For example: 

var visible = true;       // bad

var isVisible = true;    // good

var encryption = true;   // bad

var hasEncryption = true; // good
Functions

JavaScript functions are written in camel case and it is good practice to name the function as a verb in the prefix. 

For example:

// bad
function id(deptId, empId) {
 return `${deptId} ${empId}`;
}


// good
function getId(deptId, empId) {
 return `${deptId} ${empId}`;
}

The verb can be anything like get, push, fetch, compute and post. It can be kept self-descriptive. 

Class

A class in JavaScript is written in the pascal case, unlike the other JavaScript data structures. 

For example: 

class EmpName {
 constructor(firstName, lastName) {
   this.firstName = firstName;
   this.lastName = lastName;
 }
}

var me = new EmpName('Bob', 'Muller');

When the JavaScript constructor is called to exhibit a new class instance, the class name should appear in the Pascal Case. 

Overall, the name of the function should describe the purpose of the function, class, or variables. So that the other developers can easily interpret its meaning.

2. Code splitting

As your application grows the CSS and the JavaScript files increases in bytes, especially when the number of third-party libraries increases. To avoid the requirement of downloading huge files, scripts can be split into smaller files. 

So the required page can be quickly downloaded and the additional one being lazy loaded once the page becomes interactive. This helps to reduce the complexity of loading the page and improve the application performance. 

The code splitting is supported by bundlers like Webpack and Browseify. You can create multiple bundles that are easy to dynamically load at run time. 

3. Code optimization

While refactoring our first responsibility should be increasing the code readability and another one is  code optimization. Although it seems awkward, in reality, the code that is easy to understand can be efficiently optimized. And in the future, it's super easy to maintain.

The code optimization includes the following things:

  1. Elements in the <head> section should be pre-loaded before the end user sees anything on the client side: All the elements should be preloaded and ordered to load logically. Optimized pages reduce the chances of the end user seeing a completely blank page, they can gradually see the content step-by-step until the complete page gets loaded. 

  1. Exclude unused components of javascript libraries: Every developer uses libraries like jQuery UI, and React library. However, adding a library to the app includes all the possible components of each library, when you only need only a few components in it. So it's better to manage the library components that are only required for your app and exclude the remaining. 

  1. Avoid Javascript memory leaks by properly managing your scope: JavaScript memory leak refers to the situation where the app finishes using memory but it refuses to return to the underlying operating system. Every time you create an object or a variable in JavaScript, some amount of memory is consumed. This can be avoided by managing the variable and the object scope. 

  1. Avoid unnecessary variable calls: Accidental viable calls, out-of DOM references, and hanging closures can impact the performance of your app through memory leaks. Limiting the variable calls helps to reduce the chances of variable leaks and improves performance. 

4. Group functions into meaningful modules

To refactor code you should have a good understanding of the code structure and its hierarchy. Therefore every time you refactor code, try to modularize the functions with shared logic or the functions that perform similar operations.

For example: If your set of functions has two or more similar functions such as add, subtract, multiplication, and division, we can easily group them into one Math module. 

5. Refactoring code for better error handling

Does your error message describe the accurate reason behind the errors? If not, it's time to refactor it. The error message should assist the developer in determining the root cause of the error and also give the front-end user a better UI experience. 

As a developer you should

  • Always assume that your code is going to fail.
  • Log client-side  JavaScript errors on the server.
  • Identify what and where the error can occur in the code and throw errors. 
  • Identify and categorize fatal and non-fatal errors
  • Provide a way for debugging

Not only that, while error handling one should also care about the error messages. It must describe the exact reason for the error to the app user.

For example, if you are trying to log in to the application and your login attempts fail in such a case the app must give you a correct message that describes the exact reason for failure, rather than just saying “you can’t log in to the app”.Similarly, the error message should be simple to understand by the end-user.

Summing Up: 

In the article, we have learned about code refactoring and the ways you can refactor the Javascript code. Code refactoring improves software design, making the source code easy to understand, maintainable, and faster.