Gareth Redfern developer, cyclist & coffee lover

Basic Module Pattern Javascript

Posted by Gareth Redfern
Category: javascript

Basic Module Pattern Javascript

Wrap your code in a immediately invoked function expression (IFFE). It runs immediately when you create it and has no name. Normally you would create a IFFE like this:

(function() {

// your code

}());

It is common practice to remove the outer wrapping parenthesis and use a ! or + at the start of the annonymous function:

!function() {

    function foo() {
      console.log('foobar');  
    };

foo();
}();

You can pass a variable into the IFFE so that it can be used within its local scope. Here I am passing in the underscore library using _ to be used within the module.

!function(underscore) {

  console.log(underscore.VERSION);

}(_);

You can name the passed in variable (parameter) whatever you like so while you would normally use the underscore library by using _. you can now use it within the local scope using underscore. variable.

Another use might be to pass in the window object and create a variable called global within your IFFE. Now you can access the global scope by using the global variable.

var bar = "foo";

!function(global) {

    console.log(global.bar); // foo

}(window);