Portable JavaScript

June 13, 2015

Because of function scoping, browser-friendly JavaScript is frequently written as a self-contained, self-executing function:

mathz.js:

var mathz;
(function (mathz) {

  var square = function (x) {
    return x * x;
  }

  mathz.square = square;

})(mathz || (mathz = {}));

This lets other code safely reference mathz to access exported fields:

var x = mathz.square(9); // 81

In Node.js, scoping is restricted to within each file, and fields are exported using exports:

mathz.js:

var square = function (x) {
  return x * x;
}

exports.square = square;

It's inconvenient to maintain both browser and Node.js versions of a JavaScript library. Let's combine both approaches, so that we can write our code once, and have it portable between the two.

mathz.js:

var mathz;
(function (mathz) {

  var square = function (x) {
    return x * x;
  }

  mathz.square = square;

  if (exports) {
    for (var i in mathz) {
      if (mathz.hasOwnProperty(i)) {
        exports[i] = mathz[i];
      }
    }
  }

})(mathz || (mathz = {}));

Now we can distribute mathz.js, and it will work both on Web sites via <script>, and in Node.js applications via require.