Categories
JavaScript Best Practices

JavaScript Best Practices for Beginners

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.

Use === Instead of ==

=== doesn’t do data type coercion before doing comparisons.

The rules for automatic type coercion are complex so we’ll run into problems if we rely on it.

Therefore, we should use === instead of == for equality comparisons.

Also, we should use !== instead of != for inequality comparison for the same reason.

Eval is Bad

Never use eval in our JavaScript code.

It lets us run JavaScript code from a string.

This is definitely a security issue and JavaScript engines can’t optimize code in a string, so performance will take a hit.

It’s also impossible to debug code in a string easily.

Don’t Use Some Shorthands

Some shorthands are confusing, like omitting the braces for single line blocks.

For instance, we may have things like:

if (foo)
   x = false
   bar();

We may assume that both lines are part of the if block.

But only the first line is part of the block.

Therefore, we should use curly braces to delimit the blocks:

if (foo) {
   x = false;
   bar();
}

Just put them in and we’ll always be clear.

Utilize ESLint

We should use ESLint to find problems in our code and make styles consistent.

This way, we won’t have problems with inconsistency.

Also, it has built-in support for checking Node.js code.

It can also insecure code, TypeScript, JSX, and more with plugins.

Place Scripts at the Bottom of Our Page

We should put scripts at the bottom of the page so that they load after the page content has loaded.

This will make things should up faster for the user.

For instance, we write:

...
  <p>hello world</p>
  <script src="/file.js"></script>
  <script src="/anotherFile.js"></script>
</body>
</html>

to make the scripts load last.

Declare Variables Outside of the For Statement

In a for loop, we can declare variables outside of the for statement so that they aren’t declared every iteration.

For example, instead of writing:

for (let i = 0; i < someArray.length; i++) {
   let container = document.getElementById('container');
   container.innerHtml += `item ${i}`;
   console.log(i);
}

We write:

let container = document.getElementById('container');
for (let i = 0; i < someArray.length; i++) {
   container.innerHtml += `item ${i}`;
   console.log(i);
}

We move the definition of the container variable outside so that we aren’t declaring them at every iteration.

The Fastest Way to Build a String

We can build a string from a bunch of strings faster and shorter with the array instance’s join method.

For instance, we can write:

const arr = ['item 1', 'item 2', 'item 3'];
const arr.join(', ');

to combine strings together with a comma as the separator.

Reduce Globals

We shouldn’t use global variables.

They can easily be overwritten by anything.

For example, instead of writing;

var name = 'james';
var lastName = 'smith';

function doSomething() {...}

We write:

const person = {
   name: 'james',
   lastName: 'smith',
   doSomething() {...}
}

to put the items in an object.

Comment Our Code

We can put comments on our code if they don’t duplicate the code.

It’s also handy for things that we may forget.

Embrace Progressive Enhancement

Ideally, our degrades gracefully even if the user’s browser doesn’t have JavaScript enabled.

We can put a noscript tag in our HTML code to display something if JavaScript is disabled by the user.

If JavaScript is enabled, then we can display the regular content.

Don’t Pass a String to “setInterval” or “setTimeOut”

We shouldn’t pass strings into setInterval or setTimeout .

Running strings are slower since they can’t be optimized.

Also, they pose a security risk since we can pass in anything and try to run it.

And it’s very hard to debug strings.

So instead of writing:

setInterval(
"document.getElementById('container').innerHTML += `number: ${i}`", 3000
);

We write:

setInterval(() => {
  document.getElementById('container').innerHTML += `number: ${i}`
}, 3000);

Don’t Use the “With” Statement

Never use the with statement.

It’s supposed to be a shorthand to access deeply nested objects.

However, the scope is confusing.

So instead of writing:

with (person.has.bodyparts) {
  arms = true;
  legs = true;
}

We write:

person.has.bodyparts.arms = true;
person.has.bodyparts.legs= true;

with is also disabled in strict mode, so we definitely can’t use it in most places.

We can also write:

let o = person.has.bodyparts;
o.arms = true;
o.legs = true;

Conclusion

We shouldn’t use old constructs like with and passing strings into setTimeout or setInterval .

Also, we should compare things with === and !== .

Global variables should also be avoided.

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 *