// create an scope by declaring anonymous function and immediately executing it
// the return value will be assigned to myModule...
var myModule = (function(){
// return the parts of the scope to be exposed publicly
return {
someMethod: someMethod,
otherMethod: otherMethod
}
function someMethod(item){ return myPrivateSquareFunction(item) * 2; };
function otherMethod(item){ return item * 5; };
// private function can be called from in the module's scope, but not externally
function myPrivateSquareFunction(item){ return item * item; }
})();
// now, out here you can call `otherMethod`, and `someMethod` (which itself calls `myPrivateSquareFunction`) but you can not call `myPrivateSquareFunction`...
console.log(someMethod(3)); // 18
console.log(otherMethod(3)); // 15
console.log(myPrivateSquareFunction(3)); // ERROR!
By using this pattern, you can choose what implementation details remain private, and what needs to be exposed to the module. This helps you to break up your code into discreet chunks that can be worked on and tested in isolation without the rest of the application complicating it's function. Then, when you have lots of small chunks of code that do their own job correctly, and properly separated, it is an easier task to manage to assemble them into a more complex application.