Rohan Shakya
Coding Standards3 min read

Javascript Coding Standard — Clean Code

Keep your code readable, changeable, extensible, and maintainable. The code is clean if it can be understood easily by everyone.

  • javascript
  • clean code
  • coding standards
Javascript Coding Standard — Clean Code

Keep your code readable, changeable, extensible, and maintainable. 😊

The code is clean if it can be understood easily by everyone. Clean Code can be read and enhanced by a developer other than its original author.

The benefits of writing clean code are:

  • Easier to start or continue
  • Better for team onboarding
  • Easier to follow Here are some of my tips for coding standards.

1. Always use ‘let’ instead of ‘var’

Always use let instead of var because of scoping issues in JavaScript.

javascript
var ex1 = 'Medium';
let ex2 = 'Medium';

2. Always use ‘const ’ instead of ‘let’

Always use const which stops developers trying to change that shouldn’t and really helps with readability.

javascript
let TAX_RATE = 13;
const TAX_RATE = 13;

3. Always use a semicolon (;)

As semicolon is optional in Javascript, it is good practice to use a semicolon(;) which helps to keep our code consistent.

javascript
let a = 5;
if(a > 10){
  a = a * 2;
  console.log(a);
}

4. Always use === when comparing instead of ==

As == allows coercion which might give you unexpected results, always use === which checks a value and type equality.

javascript
let a = '42';
let b = 42;
a == b  //true
a === b // false

5. Naming Conventions

Always use camelCase while declaring variables and functions. If a constant variable is at the top of the file use the upper-snake case. Use PascalCase in class.

javascript
const TAX_RATE = 13;
let myCar = new Car('BMW');
function randomRange(min, max){
  return Math.floor(Math.random() * (max - min + 1) + min);
}
class MyClass {
  constructor(name, age){
    this.name = name;
    this.age = age;
  }
  printName(){
    console.log(this.name)
  }
}

6. Always use template literals when concatenating

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

javascript
const FIRST_NAME = 'John';
const LAST_NAME = 'Lennon';

const fullName = `${FIRST_NAME} ${LAST_NAME}`; // 'John Lennon'

7. Always use ES6 arrow functions where possible

An arrow function expression is a syntactically compact alternative to a regular function expression, although without its own bindings to this, arguments, super, or new. target keywords.

Arrow functions make our code more concise and simplify function scoping and this keyword.

javascript
// Normal function
let multiply = function(x, y){
  return x * y;
}

// Arrow function
let multiply = (x, y) => x * y;

8. Always use curly braces in control statements

Always use curly braces in all the control statements such as if-else, for, do, while, etc. which prevents us from silly mistakes. Also, make sure that curly braces start in the same line with space in between.

javascript
let time = 7;

if (time < 10) {
  greeting = "Good morning";
} else if (time < 20) {
  greeting = "Good day";
} else {
  greeting = "Good evening";
}

9. Always try to reduce deep nesting

An if within if can get messy and very hard to read and sometimes you may not be able to get around.

javascript
if(price > 0){
  if(price > 100){
    if(!hasDiscount){
      return addDiscount(0)
    } else {
      return addDiscount(10);
    }
  } else if ( price > 50){
    if(!hasDiscount){
      return addDiscount(5);
    } else {
      if(!hasDiscount) {
        return addDiscount(0);
      } else {
        return addDiscount(1);
      }
    }
  } else {
    error();
  }
}

So try to reduce nesting as much as possible which keeps your code readable.

javascript
if(price <= 0){
  return error;
} 
if(!hasDiscount){
  return addDiscount(0);
}
if(price > 100){
  return addDiscount(10);
}
if(price > 50){
  return addDiscount(5)
} 
return addDiscount(1)

10. Always use Ternary Operator if possible

It is a best practice to use the ternary operator when it makes the code easier to read. If the logic contains many if…else statements, you shouldn’t use the ternary operators.

javascript
function getFee(isMember) {
  return (isMember ? '$2.00' : '$10.00');
}

console.log(getFee(true));
// expected output: "$2.00"

console.log(getFee(false));
// expected output: "$10.00"

11. Always use default parameters where possible

In JavaScript, function parameters default to undefined. However, it’s often useful to set a different default value. This is where default parameters can help.

javascript
function str(name) {
  console.log(name);
}
str(); // undefined

function str(name = 'Brad') {
  console.log(name)
}
str(); // 'Brad'

12. Always use break and default in switch statements

A switch statement can replace multiple if checks. It gives a more descriptive way to compare a value with multiple variants. Make sure to use break and default from getting ‘fall through’.

javascript
let day;
switch (new Date().getDay()) {
  case 0:
    day = "Sunday";
    break;
  case 1:
    day = "Monday";
    break;
  case 2:
    day = "Tuesday";
    break;
  case 3:
    day = "Wednesday";
    break;
  case 4:
    day = "Thursday";
    break;
  case 5:
    day = "Friday";
    break;
  case 6:
    day = "Saturday";
    break;
  default:
    day = "Unknown Day";
}

13. Always declare one variable per declaration

It gets messy when you declare more than one variable at a time.

javascript
// let a = 10, b = 20;

let a = 10;
let b = 20;

14. Try to use named exports instead of the default exports

Using default export can sometimes lead to inconsistency. Give a specific name while importing modules.

javascript
// export default class MyClass{}

export class MyClass{}

15. Do not use wildcard imports

Wildcard imports can sometimes cause name conflicts and ambiguities. Two classes with the same name, but in different packages, will need to be specifically imported, or at least specifically qualified when used.

javascript
// import * as Foo from './foo';

import Foo from './foo';

Conclusion

  • Make code readable for people
  • Use meaningful names for variables, functions, and methods
  • Let one function or method perform only one task
  • Be consistent
  • Review your code regularly I hope that these practices or tips will be enough to help you get started with writing clean code. Now, like with everything, the most important thing is to get started. So, practice and try it out. 😉