Categories
JavaScript Best Practices

JavaScript Best Practices — Types and This

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.

Beware of Automatic Type Conversions

We should be aware of automatic data type conversions.

For example, we can assign any values to variables we want.

We can write something like:

let text = "james";  
text = 5;

It’s easy to change the type of variables in JavaScript.

However, we can use language extensions like TypeScript and Flow to restrict the data types of variables.

Don’t Declare Unnecessary Variables

If we aren’t using a variable, then we should remove it.

The more variables are declared, the more space they take.

For example, instead of writing:

const topBar = sidebar.querySelector('#topbar');  
const paragraph = bar.querySelector('p');  
paragraph.textContent = 'bar';

We didn’t use the the topBar variable, so we shouldn’t remove it.

We can just write;

bar.querySelector('p').textContent = 'bar';

Use Parameter Defaults

To make sure that a parameter always has a value, we should set the value of the parameter.

For example, we can write:

function logNumber(num = 100) {  
  console.log(num);  
}

This is much shorter than the old way, which is:

function logNumber(num) {  
  if (num === undefined) {  
    num = 25;  
  }  
  console.log(num);  
}

With default parameters, we don’t have to assign the parameter to a new value directly.

End Switches with Defaults

If we have switch statements, we should end them with a default clause so that we do something if none of the values match.

For instance, we write:

switch(type) {  
  case 1:  
    // something  
  case 2:  
    // something else  
  default:  
    // do something  
}

In the default clause, we can handle errors or do some default action.

eval() Is Bad

eval is definitely bad.

Running code from a string is a big security risk.

And the code can’t be optimized and hard to debug.

Don’t Use new Object()

The Object constructor don’t bring us much benefit.

It’s only longer.

We can use {} instead of new Object() .

The same advice applies to primitive value constructors.

For example, instead using new String() , we write '' .

Instead of using new Number() , we use numver literals.

And instead of new Boolean() , we use true or false .

Instead of using the Array constructor, we use [] .

However, it’s still handy for creating artays with the given numver of empty slots.

With regex, we use the regex literal like /abc/ instead of new RegExp() .

And instead of using new Function() to create our function, we use function(){} or () => {} to create it.

The code is shorter without the constructors.

And in the case of the primitive constructors, the type will be the actual type of the data instead of 'object' if we check it with typeof .

It’s also slightly faster.

Comment Our Code

We can comment on our code so explain things that aren’t described by the code.

Use Shortcut Notation When It Makes Sense

We can use shortcut notations in many cases.

For example, instead of writing:

let level;  
if (score > 200){  
  level = 2;  
} else {  
  level = 1;  
}

We can write:

let level = (score > 200) ? 2 : 1;

We use the ternary operator to check the condition and assign the value accordingly.

And instead of writing:

let price;  
if (discount){  
  price = discount;  
} else {  
  price = 120;  
}

We write:

let price = discount || 120;

If discount is truthy then it’ll be returned and assigned. Otherwise, 120 is returned and assigned.

Have One Function Per Task and Make Our Code Modular

Our code should be divided into smaller parts so that we can work with them easier.

Functions should do one thing so that we won’t be confused with they do.

This also makes it easier to test and debug.

Our code should be modular for the same purpose.

We can divide them into modules.

Learn About This

this is an important keyboard to understand. It can take on different values depending on where they are.

In a method inside the object, this is the object.

If it’s in a class, then it’s the class instance.

If it’s in a prototype function, then it’s the constructor instance.

We shouldn’t know this.

Conclusion

We should use features like parameter default values and default switch case.

And avoid things like useless constructors.

We should also learn about this , type conversion, and more.

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 *