JavaScript Best Practices — Assumptions and Optimizations
Tags: javascript, career, codenewbie, codequality
Published: 2020-10-04 00:06:10

---
title: JavaScript Best Practices — Assumptions and Optimizations
published: true
date: 2020-08-08 23:37:23 UTC
tags: JavaScript,careers,codenewbies,codequality
canonical_url: https://thewebdev.info/2020/08/08/javascript-best-practices%e2%80%8a-%e2%80%8aassumptions-and-optimizations/?utm_source=rss&utm_medium=rss&utm_campaign=javascript-best-practices%25e2%2580%258a-%25e2%2580%258aassumptions-and-optimizations
---

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**

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 the Module Pattern to Encapsulate

We can use the module pattern to encapsulate our code.

This lets us keep private variables in any JavaScript code.

For example, we can write:

```
(function(){
  let x = 123;
  console.log(x);
})();

```

We have the variable `x` that’s only available inside the function.

It’s also useful when classes or constructors don’t make sense.

### Namespace Our JavaScript

If we need to refer our JavaScript code else, we should namespace them to make them easy to find.

For example, we can write:

```
let MyNamespace = MyNamespace || {};

MyNamespace.MyModule = () => {
    // ...
}

```

our namespace has properties, which include objects we use as a module.

### Anonymously Scope JavaScript

We should scope our JavaScript if we aren’t calling it anywhere.

For example, we can write:

```
(function(){
  let x = 123;
  console.log(x);
})();

```

to scope the JavaScript to be inside the function only.

This makes our variables available only inside the function.

And we can’t modify them accidentally.

### Focus on the Big Things when Optimizing

The big performance improvements can come from a few places.

DOM operations are expensive so we should do them as little as possible.

Anything that forces a page to re-rerender isn’t optimal.

Events that are fired all the time like resizing and scrolling can also be denounced or throttled.

If we have lots of HTTP requests, we can also reduce them.

These are problems we can address to increase responsiveness.

### Lazy Load Assets that aren’t Immediately Required

If we have assets that aren’t shown to the user immediately, then we should lazy load them.

This way, they’re only loaded when they’re needed to be shown.

### `unbind()` All Event Handlers Before Binding

We should `unbind` all event handlers so that we don’ t have multiple event handlers bound to elements.

For example, we can write:

```
$("a.some-link").unbind(handleClick).click(handleClick);

```

to unbind the existing event listeners and then attach a new click listener to the `a` link.

This ensures that it’s only bound once.

Since we need this everywhere, we can create a helper function to help us do this everywhere.

### Don’t Treat JavaScript Like a Classical OOP Language

We shouldn’t treat JavaScript like a classical OOP language.

Even though the class syntax exists, it’s just syntactic sugar on top of its prototypical inheritance model.

This has never changed.

So even though JavaScript has classes, it’s not a classical OOP language.

### Don’t Abuse Inlining of Functions and Object Literals

Deep nesting is definitely bad.

They make code hard to read.

The deeper the nesting, the harder it is to follow.

For example, no one wants to read something like:

```
var myFunction = function() {
  $('form#my-form').submit(
    function(event) {
      event.preventDefault();
      $.ajax(
        '/some_service', {
          type: "POST",
          data: {
            name: name,
            name: company
          },
          success: function(data) {
            onSuccess({
              response1: data.value1,
              response2: data.value2
            })
          },
          error: function(data) {
            onError({
              response1: data.value1,
              response2: data.value2
            })
          }
        }
      );
    }
  );
};

```

We should make this easy to read by reducing nesting.

Inlining everything also makes functions and variables impossible to reuse.

### Conclusion

We can create modules to separate values.

Also, we unbind event handlers with jQuery before attaching them.

And don’t abuse inlining and treat JavaScript as a classical OOP language.

The post [JavaScript Best Practices — Assumptions and Optimizations](https://thewebdev.info/2020/08/08/javascript-best-practices%e2%80%8a-%e2%80%8aassumptions-and-optimizations/) appeared first on [The Web Dev](https://thewebdev.info).