To make code easy to read and maintain, we should follow some best practices.

In this article, we’ll look at some best practices we should follow to make everyone’s lives easier.

Unary Operators ++ and --

++ and -- both do assignment and return the value.

Their placement can change the meaning of the code.

So, we should consider using alternatives.

For instance, instead of writing:

let i = 10;
i++;

We write:

let i = 10;
i += 1;

Use of process.env

We may use configurations instead of setting environment variables.

They’re easy to replace.

For instance, instead of writing:

if (process.env.NODE_ENV === "development") {
  //...
}

We write:

const config = require("./config");

if (config.env === "development") {
  //...
}

No process.exit()

process.exit() ends the program immediately.

This means that we don’t have a chance to handle errors gracefully.

So instead of writing:

if (error) {
  process.exit(1);
}

Instead, we write:

if (error) {
  throw new Error("error happened");
}

No Use of __proto__

__proto__ is a hidden property of an object which has its prototype.

We should use Object.setPrototypeOf and Object.getPrototypeOf to set and get the prototype of an object respectively.

For instance, instead of writing:

const a = obj.__proto__;

obj.__proto__ = b;

We write:

const a = Object.getPrototypeOf(obj);

Object.setPrototypeOf(obj, b);

#web-development #technology #programming #software-development #javascript

JavaScript Best Practices — Unary Operators, and Useless Expressions
1.15 GEEK