JavaScript modules enable multiple scopes to share code. Modules use closures to keep things private and only make public certain things. Below a function is used to create a scope “bubble” for the enclosed code:

See the Pen thecodelog.com - JS Module Patterns 1 by Deano (@deangilewicz) on CodePen.

A common pattern to avoid global namespace collisions is shown below where an object is created and properties and methods are assigned to that object:

See the Pen thecodelog.com - JS Module Patterns 2 by Deano (@deangilewicz) on CodePen.

The code below shows an example of the principle of least exposure. This approach can be implemented when only wanting to expose certain things in your code outside of the function.

See the Pen thecodelog.com - JS Module Pattern 3 by Deano (@deangilewicz) on CodePen.

The following code is an example of the module pattern.

See the Pen thecodelog.com - JS Module Pattern 4 by Deano (@deangilewicz) on CodePen.

A variation on the module pattern which only cares to have one instance is shown below.

See the Pen thecodelog.com - JS Module Patterns 5 by Deano (@deangilewicz) on CodePen.

Modules can also receive parameters:

See the Pen thecodelog.com - JS Module Patterns 6 by Deano (@deangilewicz) on CodePen.

Below is another example of the module pattern variation. This time a named object is returned as the public API.

See the Pen thecodelog.com - JS Module Patterns 7 by Deano (@deangilewicz) on CodePen.