Categories
JavaScript JavaScript Best Practices

Removing Useless Expressions – JavaScript Best Practices

Spread the love

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.

No Constant Expressions in Conditions

We shouldn’t have constant expressions in conditions.

They either always run or never run if they’re present.

For instance, don’t write:

if (false) {
   foo();
}

Instead, write:

if (x === 1) {
   foo();
}

No Control Characters in Regex

We shouldn’t have control characters in a regex.

They are rarely used and it’s probably a mistake to check for them.

Instead of writing:

const pattern = /\x1f/;

or:

const pattern = new RegExp("\x1f");

We write:

const pattern1 = /\x20/;
const pattern2 = new RegExp("\x20");

instead.

Don’t Use debugger

debugger sets a breakpoint in our JavaScript code so we can inspect the variables.

This shouldn’t be in our production code.

So instead of writing:

const isTruthy = (x) => {
  debugger;
  return Boolean(x);
}

We write:

const isTruthy = (x) => {
  return Boolean(x);
}

No Duplicate Arguments in Function Definitions

Duplicate argument names isn’t valid syntax.

It’ll throw an error if strict mode is on.

Instead of writing:

function foo(a, b, a) {
  console.log(a);
}

We write:

function foo(a, b) {
  console.log(a);
}

No Duplicate if-else-if Conditions

We shouldn’t have duplicate conditions in our if statements.

The duplicate is useless and causes confusion.

So instead of writing:

if (isSomething(x)) {
  foo();
} else if (isSomething(x)) {
  bar();
}

We write:

if (isSomething(x)) {
  foo();
}

No Duplicate Keys in Object Literals

Duplicate keys are confusing and useless.

So we shouldn’t write:

const foo = {
   bar: "baz",
   bar: "qux"
};

Instead, we write:

const foo = {
   bar: "qux"
};

No Duplicate case Label

switch statements shouldn’t have more than one case label.

As with other duplicates, they cause confusion and are redundant.

So instead of writing:

switch (a) {
  case 1:
    break;
  case 2:
    break;
  case 1:
    break;
  default:
    break;
}

We write:

switch (a) {
  case 1:
    break;
  case 2:
    break;
  default:
    break;
}

No Empty Block Statements

Empty blocks are useless. So we should remove them.

Instead of writing:

if (foo) {
}

or

while (foo) {
}

or

switch(foo) {
}

We write:

if (foo) {
  bar();
}

or

while (foo) {
  bar();
}

or:

switch(foo) {
  case 1:
    //...
    break;
}

Conclusion

We shouldn’t have duplicates of most things.

Also, we should remove control characters from regexes and debugger.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *