Categories
JavaScript JavaScript Best Practices

More JavaScript Habits we can Follow

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 Reassigning Exceptions in catch clauses

We shouldn’t reassign the error object in the catch clause.

Instead, we should assign it to a new variable to ensure that we don’t lose any information.

For instance, instead of writing:

try {
  // ..
} catch (e) {
  e = 10;
}

We write:

try {
  // ...
} catch (e) {
  const foo = 10;
}

No Unnecessary Boolean Casts

If we already have a boolean variable, then e don’t need to cast it again.

For instance, instead of writing:

var foo = !!!bar;

var foo = !!bar ? baz : bat;

var foo = Boolean(!!bar);

var foo = new Boolean(!!bar);

We write:

var foo = !bar;

var foo = bar ? baz : bat;

var foo = Boolean(bar);

var foo = new Boolean(bar);

Boolean and !! already does the casting so we don’t have to do it again.

No Innecessary Parentheses

We shouldn’t have extra parentheses in our code.

For instance, instead of writing:

a = (b * c);

(a * b) + c;

We write:

a = b * c;

a * b + c;

We skip them to save some typing and make them easier to read.

No Unnecessary Semicolons

We shouldn’t have more semicolons than it’s necessary.

For example, instead of writing:

var x = 10;;

function foo() {
  // code
};

We write:

var x = 10;

function foo() {
    // code
}

No Reassigning Function Declarations

We shouldn’t reassign function declarations.

Instead, we assign whatever we want to assign to a new variable.

For instance instead of writing:

function foo() {}
foo = bar;

We write:

var foo = function () {}
foo = bar;

If we create a function, then keep it a function.

No Assignment to Imported Bindings

If we have imported bindings, then we should use it directly or as to rename it.

Otherwise, we assign what we have to a new variable and then work with it.

For instance, we write:

import mod from "./mod"

mod.prop = 1;

And not:

import mod from "./mod"

mod = 1;

No Variable or Function Declarations in Nested Blocks

We shouldn’t have function declarations in nested blocks.

It’s invalid syntax even though it’s accepted.

For instance, instead of writing:

if (test) {
    function doWork () { }
}

We write:

function doWork () { }

We can also write nested declarations:

function doSomething() {
  function doAnotherThing() {}
}

Conclusion

We shouldn’t use invalid syntax.

Also, redundant code is bad.

Extra parentheses should be removed to save us typing and space.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.