macbook pro on a table

JavaScript: simple code structure for libraries

By

in

The code of a JavaScript library might get very complex over time. This can be a problem for maintenance and expandability.

When writing a library, you should address two main points:

  • Keep the environment clean from global variables and methods to avoid conflicts between different libraries
  • Provide public and private methods and variables

The following “template” provides a simple code structure that fulfills those points:

// Unique name of the library.
MyLibrary = function() {
  MyLibrary = {};

  /*
   * Internal variables and methods
   */
  var variable = 'value';
  function doSomething() {
    // do something
  }

  /*
   * Public variables and methods
   */
  MyLibrary.myVariable = true;
  MyLibrary.myAction = function() {
    // do something
  }

  // Return the library.
  return MyLibrary;
}

You can use such a library the following way:

const lib = MyLibrary();
lib.myAction()

if (lib.myVariable) {
  alert('really?');
}

Inspiration: https://stackoverflow.com/questions/13606188/writing-a-library-what-structure

Photo by Safar Safarov on Unsplash



Comments

One response to “JavaScript: simple code structure for libraries”

  1. From a readability point of view, its is great but I think using ES6 class will do the similar job without any hassle.

Leave a Reply

Your email address will not be published. Required fields are marked *