Clean Code In Javascript

Hi,

I am a software developer, primarily working on the javascript language. While working on the lots of code. I realized the importance of the clean code.

So, I want to share my experience with everyone.

So, while writing javascript code. Keep these things in mind.

Code Editor & Tools

Most developers use Visual Studio Code these days. You can use any code editor that you want. However, tools like Prettier can be integrated into most modern code editors. Prettier can also be run via command line to automatically format files as per provided specification. A good read is available at prettier.io.

Example .prettierrc.json file.


{
    "tabWidth": 4,      // make tab width equal to 4
    "semi": true,       // semicolon after the statement ends
    "singleQuote": true // all the string will be using single quote
}

var vs let/const

Never use var to define variables. Always use let or const. I follow a golden rule; if there's no need to reassign another value to a variable after it's first assigned something, then it should be a const. If you need to reassign something else to the same variable, it should be a let.

An alternative is to always define a variable with const. If in the code somewhere, you are reassigning it, then the code will throw an easily recognizable error and you just change const to let.

Variable names

Avoid using generic variable names such as const i = 'jatin'. Use a proper name that tells what the variable is about. For example, if the variable represents, a user name then, it should be const user = 'jatin'

Comparison == vs ===

Never compare two variables/values with double equal. It is not reliable, because 1 == true is correct with double equals, despite the fact that 1 is a number and true is a boolean.

The == just compares value, the === compares the value as well as the type.


-> 1 == '1'  // true : values are same
-> 1 === '1' // false : values are same but type is different
-> 1 === 1   // true : both value and types are equal

Always compare with triple equal.

Set maximum line width in code editor settings

A line should not be more than 80 spaces/print-width longs. If it is, then the code shall be split into multiple lines.

Always use the brackets when using conditional statements

It makes the code more readable.

// Bad code
if (isCurrent)return 'foo';

// Good code
if (isCurrent) {
    return 'foo';
}

Use proper bracket spacing for the good readability

Have proper bracket spacing as well.

// Bad code
const array = [1,2,3];
const person = {name:'John',age:25};

// Good code
const array = [1, 2, 3];
const person = { name: 'John', age: 25 };

Destructuring

Always try to de-structure when possible. I am going to give two examples here.

Default method

const user = getUser();
console.log(user.name);
console.log(user.age);

Recommended method

const { name, age } = getUser();
console.log(name);
console.log(age);