JavaScript Best Practices — Using Classes and Modules

December 31st, 2021
2
mins read
Photo by David Clode on Unsplash
Photo by David Clode on Unsplash

JavaScript is a very forgiving language. It’s easy to write code that runs but has mistakes in it.

In this article, we’ll look at what should be in our class methods, and also the best ways to use modules.

Class Methods Should Either Reference this Or Be Made Into a Static Method A JavaScript class can have static or instance methods. If it’s an instance method , then it should reference this . Otherwise, it should be a static method.

For instance, we should write a class that’s like the following code:

class Person {
  constructor(name) {
    this.name = name;
  }
  static greet() {
    return 'hi'
  }
  greetWithName() {
    return `hi ${this.name}`;
  }
}

In the code above, we have the static greet method which doesn’t reference this and the greetWithName method, which references this.name .

Static methods are shared with all instances of the class and instance methods are part of the instance, so it makes sense it references this .

Use ES6 Modules Import and Export Over Non-Standard Module Systems With ES6, modules are a standard feature of JavaScript. We can divide our code into modules and only export code that we want to expose to the outside.

Also, we can selectively import members from another module.

Before ES6, there’re various module systems like RequireJS and CommonJS. They’re similar to what ES6 modules do today. However, ES6 modules can do what they do and they’re a JavaScript standard.

Therefore, we should just use ES6 modules over other kinds of modules so that we won’t have to worry about those kinds of modules going away or compatibility issues with other kinds of module systems.

For instance, instead of writing the following code to export and import modules:

module.js
module.exports = {
  foo: 1
};
index.js
const { foo } = require("./module");
console.log(foo);