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.

Use {} Instead of New Object()

We should use object literals instead of new Object() .

The constructor has no benefits over object literals and it’s longer.

Instead of writing:

let o = new Object();
o.name = 'james';
o.lastName = 'smith';
o.greet = function() {
   console.log(this.name);
}

We write:

const o = {
   name: 'james',
   lastName = 'smith',
   someFunction() {
      console.log(this.name);
   }
};

We can write:

const o = {};

to create an empty object.

Use [] Instead of New Array()

The Array constructor is longer and doesn’t bring much benefit.

However, we can create an array with a given number of empty slots with it.

So we can use it with one numerical argument to create an empty array with the number of slots.

Other than that, we use array literals.

For example, instead of writing:

const a = new Array();
a[0] = "james";
a[1] = 'smith';

We write:

const a = ['james', 'smith'];

To create an empty with the Array constructor, we write:

const a = new Array(10);

This creates an empty array with 10 slots.

#programming #web-development #technology #software-development #javascript

More JavaScript Best Practices for Beginners
1.25 GEEK