Categories
JavaScript JavaScript Best Practices

More JavaScript Habits we can Follow

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.

Categories
JavaScript JavaScript Best Practices

Removing Useless Expressions – JavaScript Best Practices

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.

Categories
JavaScript JavaScript Best Practices

Basic JavaScript Best Practices

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.

Having the Correct for Loop Direction

We should make sure that we update the index variable in the right direction so that we don’t get infinite loops.

For instance, the following is probably wrong:

for (var i = 0; i < 10; i--) {
}

The loop never ends since i is being decremented in each iteration.

Instead, we should write:

for (var i = 0; i < 10; i++) {
}

so that the i variable gets to 10.

Return Statement should be Present in Property getters

If we define a getter, then we should return something.

Otherwise, the getter is useless.

For instance, instead of writing:

const obj = {
  get name() {
    
  }
};

We write:

const obj = {
  get name() {
    return 'james'  
  }
};

or:

 Object.defineProperty(person, "age", {
   get() {
     return 17;
   }
 });

No async Function as a Promise Executor

We shouldn’t have async functions in our Promise constructor.

This is because async functions already returns promises, so it’s redundant.

For instance, we shouldn’t write;

const result = new Promise(async (resolve, reject) => {
  resolve(await foo);
});

or:

const foo = new Promise(async (resolve, reject) => {
  readFile('bar.txt', (err, result) => {
    if (err) {
      reject(err);
    } else {
      resolve(result);
    }
  });
});

It’s completely redundant to have them.

Instead, we write:

const foo = new Promise((resolve, reject) => {
  readFile('bar.txt', (err, result) => {
    if (err) {
      reject(err);
    } else {
      resolve(result);
    }
  });
});

or:

const result = Promise.resolve(1);

No await Inside Loops

We should move await outside of promises that can run in parallel.

So instead of writing:

copnst foo = async (things) => {
  const results = [];
  for (const thing of things) {
    results.push(await bar(thing));
  }
  return baz(results);
}

We write:

const foo = async (things) => {
  const results = things.map(thing =>bar(thing));
  return baz(await Promise.all(results));
}

We map the things entries to promises.

Then we use Promise.all to run all the promises in parallel.

No Comparison Against -0

Comparing against -0 won’t work as intended.

Instead, we compare an expression with 0.

So instead of writing:

if (x === -0) {
  //...
}

We write:

if (x === 0) {
  //...
}

We can use Object.is to compare against -0:

if (Object.is(x, -0)) {
  // ...
}

Object.is distinguishes between +0 and -0.

No Assignment Operators in Conditional Statements

Assinging things in operators is probably a mistake if we don’t compare it against something.

For instance:

if (user.title = "employee") {
  //...
}

isn’t comparing user.title to 'employee'.

Instead, we write:

if (x === 0) {
   b = 1;
}

to make sure we’re comparing against an expression.

Remove console from Production Code

We shouldn’t run console.log when our code goes to production.

Therefore, we should remove them.

It’s good for debugging but we should remove them before we check in our code.

Conclusion

We should take note of some basic best practices when writing JavaScript code.

Don’t use async and await with the Promise constructor.

Don’t write infinite loops unintentionally.

And return things in getters.

Also, don’t assign variables unintentionally in our if statements.