Writing a clean and maintainable javascript code means it increases the code quality and improve code readability 

1. Use Clear and Meaningful Names for Declaration:

Write names that describe the purpose of the variable or functions. Avoid short and ambiguous names that could be confusing to the other developers. Use consistent naming throughout your code. This makes it easier to read,understand and also helps to avoid naming conflicts.

Example:

Const userName = ’john’;
Let age = 12;
Let isLoggedIn = ’false’;

// clear and meaningfull naming for declaration

2. Declare Variables:

Declare variables and assign values to them instead of using values directly. By declaring variables, you can reuse the same value multiple times in your code without having to repeat it. Use camelCase naming conventions to declare variables.

Example:

Const message=”Hello”;
Const userName=”John”;

console.log(message);
console.log(message+” “+userName);

// like this we can use variables when where we have requirement

3. Use Comments:

Comments help to explain the concept of the code and functionality. It helps the others to understand the code and reasoning behind it.

But don’t write for every single line. Comments can be good but your code should be self documenting it should speak for itself.

Example:

// This function checks if a given number is even or odd

function checkEvenOrOdd(num) {
// check if the number is even
   If (num%2 === 0) {
        return “even”; 
   } else {
        return “odd”;
   }
}

const result = checkEvenOrOdd(6); // calling the function
console.log(result);

4. Use Formatters:

Consistent formatting and indentation are important for writing clean and maintainable code. It improves the readability of the code and makes it easier to understand and maintain. There are many popular code formatting tools available such as Prettier,ESLint and JSHint. Which can help enforce a consistent coding style across the entire code base.

There are multiple ways to install Prettier,ESLint and JSHint in VS Code. Some of them:

1. Using the VS Code Marketplace

2. Using a package manager

3. Installing locally in our project

4. Using a task runner

5. Avoid Code Duplication:

Avoiding code duplication is also an important best practice for writing clean and maintainable code. By extracting reusable code into separate functions or  modules, you can make your code more modular, easier to maintain, and reduce the likelihood of introducing bugs.

There are many third-party libraries available to provide reusable code and can help you to avoid the code duplication.

Bad Example:

function calculateArea(length, width) {
return length * width;
}

function calculateVolume(length, width, height) {
return length * width * height;
}

const area = calculateArea(2, 3);
const volume = calculateVolume(3, 4, 5); 

Good Example:

function calculate(length, width, height=1){
return length*width*height;
}

const area = calculate(2,3);
const volume = calculate(4,5,6);

6. Use Const and Let Instead of Var:

The const and let keywords were introduced in ES6 and are block-scoped, meaning they are only available  within the block of code they  are defined in, while the var keyword as function scope, which can lead to unexpected behavior. Using const and let can improve the readability and maintainability of the code. When You use const,you are indicating that the variable will not be reassigned.When you use let,you are indicating that the variable may be reassigned.

7. Use Strict Mode:

“Use strict” when this statement is included at the beginning of the file or function. This means that the  javascript engine will enforce stricter rules when executing your code.

Using strict mode can help to prevent common errors like undeclared variables, assigning values to non-writable properties, duplicate property names in an object literal, using eval functions and increasing the readability of code.

Example:

‘use strict’;

//This function has a syntax error because it tries to assign a value o an undeclared variable

function myFunction(){
x=10;
return x;
}

//This will throw an error in strict mode,preventing the function from running

console.log(myFunction());

8. Use Optional Chaining:

Optional chaining allows you to access properties and methods of an object without having to worry about whether intermediate properties exist or not.It uses the ‘ ?.’ operator to check the property or method exits before attempting to access it.If property or method doesn’t exist , The expression returns ‘undefined’.

Example:

const person = {
name : ’John’,
age : 22,
address : {
       city : ‘hyderabad’
              }
};

// without optional chaining
const city1 = person.address && person.address.city;
console.log(city1);

// with optional chaining
const city2 = person.address?.city;
console.log(city2);

9. Avoid Nesting Too Deeply:

Yes, nesting too deeply can make code difficult to read and maintain and it also leads to performance issues. So break up complex logic into smaller functions, use early returns, use switch statements and use arrays and loops. Using these tips you can avoid deep nesting and create more maintainable javascript code.

Example:  

//In this function using javascript methods we are avoiding nesting
function processUsers(users) {
users?.filter(user=> user?.isActive)
           ?.flatMap(user => user?.orders?.filter(order => order?.status === ‘pending’))
           ?.flatMap(order => order?.items?.filter(item => item?.price> 50 ))
           ?.forEach(item=> {
            console.log(item);
    });
}

Author Information

Sowjanya Morampudi is an Associate software development engineer with a passion for exploring the latest Frontend Technologies for providing the best user experience in the products and creating elegant solutions. Pushing the boundaries of technology.