Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Javascript Interview Question: Revealing Module Pattern
Use the module pattern to group together similar methods such as database services.
In the example below, the ItemDao (Data Access Object) simulates several functions
that interact with a database.
1. Use modules to encapsulate related functionality.
2. A module pattern at its core is an object literal.
3. When using the module in code, call the functions using the key/value syntax.
For example: itemDao.findOne(1);
4. Wrap the object into a function to create a closure for private variables. Examples
of private variables would include database credentials, connection string values, etc.
These are private variables and are not accessible from the code.
5. Keep in mind, a difference between the module pattern and the constructor pattern is that
we generally will have only one instance of the service. We will reuse it, where as, the
constructor pattern creates new instances of objects.
var ItemDao = function() {
let db = {
1: { name: 'Coffee', price: 1.50, type: 'beverage' },
2: { name: 'Espresso', price: 2.25, type: 'beverage' },
3: { name: 'Latte', price: 3.50, type: 'beverage' },
4: { name: 'Biscotti', price: 3.50, type: 'food' },
5: { name: 'Muffin', price: 3.50, type: 'food' }
function findOne(id) {
return db[id];
function findByType(type) {
let resultSet = [];
for (let key in db) {
if (db[key].type === type) {
return resultSet;
//Our public interface for ItemDao.
return {
let itemDao = new ItemDao();
let item = itemDao.findOne(2);
console.log(`Your ${} will cost $${item.price}`);
let items = itemDao.findByType('food');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.