Categories
JavaScript Best Practices

JavaScript Best Practices — Exceptions, Loops, and Returns

Spread the love

Like any kind of apps, JavaScript apps also have to be written well. Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some best practices we should follow when writing JavaScript code.

No Multiple Spaces Inside Regex Literals

We shouldn’t have multiple spaces inside regex literals.

For instance, we shouldn’t write:

const regex = /foo  bar/;

Instead, we write:

const regexp = /foo bar/;

Assignment in return Statements Must be Surrounded by Parentheses

We should surround return statements in parentheses so we can be sure that the assignment is being done before returning the value.

For instance, instead of writing:

function add (a, b) {
  return result = a + b;
}

We write:

function add (a, b) {
  return (result = a + b);
}

Don’t Assign a Variable to Itself

Assigning in a variable to itself is a useless statement, so we shouldn’t write it.

For instance, we shouldn’t write things like:

num = num;

Don’t Compare a Variable to Itself

Since comparing a variable to itself is always true , it’s useless to have a variable compared to itself.

For instance, we shouldn’t write:

if (score === score) {}

Don’t Use the Comma Operator

The comma operator always returns the last expression in the sequence, so it’s pretty useless.

Therefore, we shouldn’t have code like:

const foo = (doSomething(), !!test);

Don’t Assign Things to Restricted Names

We shouldn’t create variables with restricted names and assign values to them.

It doesn’t work and it just causes confusion.

For example, we shouldn’t have code like:

let undefined = 'value';

No Sparse Arrays

We can have arrays that don’t have an entry in even slot.

To do that, we just write commas with nothing in between it to create sparse arrays.

However, this can easily be mistaken for a typo, or that it is a typo.

Therefore, we shouldn’t have expressions like that.

For instance, we shouldn’t write things like:

let fruits = ['banana',, 'grape'];

No Tabs

Tabs cause issues with different text editors.

The spacing from tabs are inconsistent between them,

Therefore, we shouldn’t use them.

Instead, we use 2 spaces or convert tabs to 2 spaces automatically for indentation.

Regular Strings Should Contain Template Literal Placeholders

It’s easy to mistaken template strings and regular strings since they use similar characters as delimiters.

We can’t have template literal placeholders in regular strings.

Therefore, we shouldn’t have code like:

const greeting = 'hi  ${name}';

Instead, we write:

const greeting = `hi  ${name}`;

Template strings are delimited with backticks rather than single quotes.

super Must be Called Before this

In class constructors, we must call super before this .

Otherwise, we should get an error.

Therefore, instead of writing:

class Dog extends Animal {
  constructor () {
    this.breed = 'chow chow';
    super();
  }
}

We write:

class Dog extends Animal {
  constructor () {
    super();
    this.breed = 'chow chow';
  }
}

Always Throw Error Instances

An Error instance has useful information like stack traces and line number where the error is.

Therefore, we should always throw Error instances instead of other values.

So we shouldn’t write:

throw 'error';

But we should write:

throw new Error('error');

Whitespaces Shouldn’t at the End of a Line

Whitespaces shouldn’t be at the end of a line.

They don’t do much. So we should remove them.

Don’t Initialize to undefined

We shouldn’t initialize a variable to undefined .

A variable is already undefined when we declare them without value.

So we don’t need to set it to undefined explicitly.

For instance, instead of writing:

let name = undefined;

We just write:

let name;

No Unmodified Conditions of Loops

If we forget to update the condition, then we’ll probably get an infinite loop.

Therefore, we should remember to modify the condition in each iteration.

For instance, instead of writing:

for (let i = 0; i < arr.length; j++) {...}

We write:

for (let i = 0; i < arr.length; i++) {...}

Conclusion

We shouldn’t have loops that have conditions that don’t update.

Also, we shouldn’t have useless spaces in our code.

Throwing Error instance is better than throwing other values since it provides more information.

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 *