Skip to main content

A practical JavaScript module example.

/*
  Principles of Writing Consistent, Idiomatic JavaScript

  Complete article and examples is here:
    - https://github.com/rwldrn/idiomatic.js
*/

(function( global ) {

  var Module = (function() {

    var data = "secret";

    return {

      // This is some boolean property
      bool: true,

      // Some string value
      string: "a string",

      // An array property
      array: [ 1, 2, 3, 4 ],

      // An object property
      object: {
        lang: "en-Us"
      },

      getData: function() {
        // get the current value of `data`
        return data;
      },

      setData: function( value ) {
        // set the value of `data` and return it
        return ( data = value );
      }
    };

  })();

  // Other things might happen here

  // expose our module to the global object
  global.Module = Module;

})( this );