JavaScript Module Pattern

Modules are needed in JavaScript to achieve modularity, which is to keep pieces of code that is unrelated to be independent from one another in a loosely coupled way (changes in one affects little to no effects to another).

These sort of module patterns are popular when module bundler like Webpack is still not a thing.

Modularity is considered by many to be well-structured code.

It's the idea of separation of concern. Revolves around the principle of high cohesion and low coupling.

Module provides encapsulation and avoid namespace collision. It acts as a replacement of class.

Encapsulation is something that JavaScript natively doesn't have. To counter this, we use something called closure. It provides private variable/method.

To sum that:

  • provide encapsulation

  • support modularity

  • avoid namespace collision

Module design pattern uses something referred to as IIFE (immediately invoked function expression), it's simply a function that wraps inside of a parentheses.

let iife = (function () {  
  ...
})();

or,

let iife = (function () {  
  ...
}());

The parentheses tells JavaScript engine that what's inside has to be an expression, therefore it knows when it encounters a function, the function has to be a function expression, not a function declaration.

There is also an important feature JavaScript has that you need to know, it is known as implied globals.

On a non global execution context, let's say something like this:

function foo () {  
  undeclaredVar = 3;
}
foo();  
console.log(undeclaredVar); // outputs 3  

Although undeclaredVar has not been declared prior, it still works!

JavaScript engine will check whether undeclaredVar is available in the current execution context, if not, then it will check it's parent execution context and see if it's there. If it's fruitless, then JavaScript engine will treats it as a global variable (freshly created with the corresponding assignment as the value).

Bear in mind that implied globals will not work in the global execution itself on strict mode!

a = 3; // throws error  
Revealing Module Pattern

This is the basic module pattern you'll use and often see to create a module. You probably saw it in another types of pattern (not just module pattern) such as factory.

let awesomeModule = (function () {  
  // private variable goes here
  return {
    // public variable goes here
  };
})()
Privilege Member

Privilege members are used to access private members indirectly. It's like a setter and getter. An advantage is to be able to filter and protect private members for being accidentally altered with an unexpected value or solely errors.

let awesomeModule = (function () {  
  let numFoods = 10;
  return {
    setFood(numFood) {
      if (typeof numFood !== 'number') {
        throw Error('setFood require number parameter');
      }
    }
  };
})()
Augmentation

This is a module pattern used to add additional properties to our current module. It is divided into two distinct variance:

  • Loose augmentation

  • Strict augmentation

Tight augmentation requires module to load synchronously (in order), while strict augmentation does not.

Tight Augmentation:
module = (function (module) {  
  module.newProp = 'bar';
  module.newMethod = () => {};
  return module;
})(module)

So it is no longer creating but instead adding.

Notice that is passes module, therefore module needs to already been initialized (otherwise it will be undefined).

I don't really know the importance of returning and reassigning the module on this pattern. I guess it's purpose is generally consistency.

Loose Augmentation:
let module = (function (module) {  
  module.newProp = 'bar';
  module.newMethod = () => {};
  return module;
})(module || {})

Loose augmentation does not requires you to provide an existing module.

Now in this case, it is important to return the module and reassign it, just in case that the module does not exist in the first place. Otherwise, no augmenting will ever takes place.

As for the expression module || {} it will returns {} when module is falsy. You can think {} as a default.

The only downside is incapability to overwrite methods.

Sub-Module

Nothing special here, creating a sub-module is as simple as creating a module:

module.subModule = (() => {  
  return {};
})()

Brief Note on JavaScript Promises and Async/Await

Promise has the following syntax:

new Promise((resolve, reject) => {  
  // code goes here...
});

Invoking resolve() will returns a resolved promise.

let resolvedPromise = new Promise((resolve, reject) => resolve());  

Invoking reject() will returns an rejected promise.

let resolvedPromise = new Promise((resolve, reject) => reject());  

Throwing an error inside a .then will returns a rejected promise:

  Promise.then(() => throw new Error());

.then() will be executed if prior promise resolves, returns a rejected promise if prior promise is rejected.

.catch() will be executed if prior promise rejected, returns a resolved .

An unhandled rejected promise will not stop execution context from running, and is not handled the way normal throws (in try catch block).

Async function must yield (await) a promise!

Invoking an async function will returns a promise that resolves when the async function returns (pop), resolved with the returned value from the async function itself.

async().then((resolvedVal) => console.log(resolvedVal))  

If the returned is a promise, then it will resolved when the returned promise as in:

.then(() => new Promise((res, rej) => 2))

If none is explicitly returned, then it returns undefined as the resolved value.

Async functions are generators, which means it yields, where yield is equivalent to await. And it must yield a promise.

If the yielded promise resolves, it will continue executing the async function and pass along the resolved value back to it.

If it yields a promise that is rejected, the async function will returns with a rejected promise.

I currently have no idea how a async as a generator knows when it is done internally. What I mean is:

async function a() {  
  await new Promise((resolve, reject) => resolve());
  console.log('foo');
}
a().then((res) => console.log('bar'));  

This will outputs foo and bar respectively.

I was thinking that when it yields an object where .done() is true, then the async function will resolved, but apparently that is not the case.

JavaScript Design Pattern

Pattern is something I heard a lot in the developer community. Might be awesome to get some deeper insight what it actually is.

Without further ado, lets dive together on learning Design Patterns! I'll be using Addy Osmani's book, Learning JavaScript Design Patterns*, as a reference.

What is a Pattern, anyway?

Patterns are proven approach on solving over a recurring problems we might encounter during code production.

It matters because it has been tested over and over again on lots of scenarios.

Rather than having to write our own approach only to realize that it's not working as you might expected. Not saying that you shouldn't, but it would be wiser in terms of efficiency and effectivity to use an existing pattern.

Addy Osmani state the following advantages of pattern on his book, JavaScript Design Patterns:

  • Preventing minor issues (edge cases).

  • Applicable to lots of scenarios (not tied to a specific problem).

  • May decrease file size by reducing repetition also known as DRY (don't repeat yourself).

  • Add to a developer's vocabulary.

  • Improved over time through collective experience.

Know It's Brother

Design Pattern has it's opposite, named anti-pattern.

Well, as you might guess, it is a pattern that sucks!

Apparently it has been known for quite some time that using an anti-pattern leads to destruction.

So it might be better to just avoid it.

An example of anti-pattern is using document.write due it's capability to overwrite your whole document. Disaster indeed.

Patterns Into Sections

Patterns generally divided into three major classifications:

  • Creational

  • Structural

  • Behavioral

Take a closer look of the following image (taken from Slideshare):
JavaScript Design Pattern

I'll be covering each and every one of these into several blog posts.

Pattern Table of Content

JavaScript Constructor Pattern

There are 3 ways to create an object in JavaScript:

let object1 = {};

let object2 = Object.create(Object.prototype);

let object3 = new Object({key: val, ... });  

The first option is an object literal where basically is a key-value pair.

The second lets you specify the prototype for the object you're trying to create. You'll able to see it by accessing object2.__proto__. You'll need to specify the prototype or otherwise it will throws.

Remember that every object inherits Object.prototype by default.

So for instance, object1.__proto__ will be equivalent to Object.prototype without be obliged to specify the prototype by yourself. But for the second option, you'll be needing to sepcify Object.prototype by yourself.

The following achieve the same result as the third option:

Object({key: val, ... });  
Accessing and Mutating Props

You'll mainly use either dot notation . or a bracket notation [].

For setting/assigning a new property, you can also use Object.defineProperty(), by the following syntax:

Object.defineProperty(obj, prop, descriptor)  

There are two type of descriptor, you can only choose either of these, otherwise it will throws.

  • data descriptor
  • accessor descriptor

Both have the following key:

  • configurable: are the descriptor mutable?
  • enumerable: will the property shows up during enumeration (for ... in and Object.keys).

For data descriptor:

  • value: well, the value for the property.
  • writable: is the property mutable?

Ex:

Object.defineProperty(obj, 'awesomeKey', {  
  enumerable: false,
  configurable: false,
  writable: false,
  value: 'Some random awesome value'
});

There are defaults for every of these descriptor keys, so you don't have to explicitly specify for each.

But if you don't, there is a possibility where the options are inherited from the prototype chain. I'm not really sure about this, though...

For accessor:

  • get
  • set

Both get and set are function that will be executed when you either assign or access the corresponding key. For instance:

let Cat = {};  
Object.defineProperty(Cat, 'age', {  
    get: function() {
      return this.age || 10;
    },
    set: function(value) {
      this.age = value;
    }
  });

console.log(Cat.age); // returns 10  
Cat.age = 12;  
console.log(Cat.age); //returns 12  

Why Redux Use Pure Function

Before going straight to the question, let us steal a piece of code from Redux that features combineReducers() function.

It seems that my previous understanding on how Redux implements combineReducers() does not aligns with the current implementation.

Here's my prior understanding on how it works:

const combineReducers = (reducers) => {  
  return (state = {}, action) => {
    return Object.keys(reducers).reduce(
     (nextState, key) => {
       nextState[key] = reducers[key](
         state[key],
         action,
       );
       return nextState;
     },
     {});
  }
}

Current Implementation:

var reducerKeys = Object.keys(reducers);  
var finalReducers = {};  
for (var i = 0; i < reducerKeys.length; i++) {  
  var key = reducerKeys[i];
  finalReducers[key] = reducers[key];
}
var finalReducerKeys = Object.keys(finalReducers);

return function combination() {  
    var state = arguments[0];
    var action = arguments[1];

    var hasChanged = false;
    var nextState = {};
    for (var i = 0; i < finalReducerKeys.length; i++) {
      var key = finalReducerKeys[i];
      var reducer = finalReducers[key];
      var previousStateForKey = state[key];
      var nextStateForKey = reducer(previousStateForKey, action);
      if (typeof nextStateForKey === 'undefined') {
        var errorMessage = getUndefinedStateErrorMessage(key, action);
        throw new Error(errorMessage);
      }
      nextState[key] = nextStateForKey;
      hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
    }
    return hasChanged ? nextState : state;
  };

Note: several lines of code are stripped for simplicity sake.

As you can see it is no longer using the reduce() as it was.

It is making certain optimization by considering whether the new state of the corresponding reducer has changed.

If one of the state changes, then it will return the whole new state. Otherwise if none changes ( nextStateForKey !== previousStateForKey keeps returning false ), it will return the previous state, and I assume there won't be any re-rendering.

Redux does this to ensure efficiency. Why re-renders if the state is equivalent as it was.

Due it's deterministic behavior, it will outputs the same result with the same input.

This leads to the question...

Why Pure Function?

As you saw in the preceding code, the combination() determines whether returning a new state is necessary through === operator, which is far efficient than a deep comparison.

Making any mutation to a state (and returning the mutated state) will make the comparison (hasChanged) results to false, which is not something we want to have (because a change HAS occur!).

Now.

One of the characteristic of pure function is it's prohibition to
mutate the arguments the function receives.

It matches exactly on how a reducer needs to be designed!

Every time a changes is made upon a state, a reducer has to return a new fresh state, and NOT making changes to the argument (previous state), therefore making it easier for Redux to tell whether it a change has occur.

It's that simple.

Using Redux Saga To Manage Your Side Effects

If you’re using Redux anytime by now, you’ll realize as your codebase goes large, so does your side effects. And by side effects I mean data fetching, or any async processes that needs special treatment.

Previously people would suggest to use redux-thunk, which basically is an action creator that returns a function, in which it will be invoked in your middleware. But it has it’s own challenges:

  • it’s not testable
  • no concurrency
  • the bigger the codebase, the more complicated it will be

Having Redux Saga as one of your dependency will tremendously makes life much easier as it abstracts complex async operation beneath the library’s core.

There are several prerequisite before proceeding to look for Redux Saga, you need to understand about generators and promises, better yet, async-await style.

This is because Redux Saga uses generators. Implementing a saga requires you to keep yielding stuff.

I suggest you to read the following beforehand:

Introduction

Redux Saga === Middleware

Yup, Redux Saga is just another kind of middleware that will intercept any of your dispatched action before handing it over to your reducer.

Getting Started

Because it’s a middleware, you need to specify your saga when creating your Redux store.

import {  
  createStore,
  applyMiddleware,
} from 'redux'
import createSagaMiddleware from 'redux-saga'  
import reducer from './reducers'  
import mySaga from './sagas'

// create the saga middleware
const sagaMiddleware = createSagaMiddleware()  
// mount it on the Store
const store = createStore( reducer, applyMiddleware(sagaMiddleware) )  
// then run the saga
sagaMiddleware.run(mySaga)  

This code is taken from the official documentation.

Watcher and Worker Saga

Generally you’ll have two kinds of saga:

  • Watcher Saga

  • Worker Saga

Watcher Saga watches for any incoming dispatched action.

When it receives one, it will spawns/initiate a worker saga, often referred to as a task, which will do the work.

I like to think a task as just another layer of middleware, but with a special ability of pausing and resuming.

Therefore, you can initiate multiple of worker saga/tasks at the same time, each will work concurrently.

Effects

You’ll see from the preceding code there’s a magic call  and put  invocation. call *and *put doesn’t directly invoke a function that does the work, instead it returns an instruction for the middleware to execute.

Here’s what it looks like:

{
  CALL: {
    fn: Api.fetch,
    args: ['./products']
  }
}

This kind of pattern is seen in a lot of libraries, including React’s React.createElement().

Redux Saga call this as an effect.

Call and put is two of several other effects Redux Saga introduces, but frankly you won’t need all.

Combining it all

Here’s what a typical watcher and worker saga would look like:

// defining your watcher saga
function* watcherSaga() {  
  yield takeLatest('FETCH_ALL_USERS_DATA', workerSaga);
}
// defining your worker saga
function* workerSaga(action) {  
  yield fetchResult = call(httpRequest);
  yield put({
    type: 'FETCH_RECEIVED',
    payload: fetchResult,
  });
}

Take a closer look on mySaga from the previous chunk of code, and that will be your saga’s starting point.

You’ll generally will always start with a watcher saga, it means that mySaga will be a watcher saga.

On this sagaMiddleware.run(mySaga) line of code, Redux Saga will directly runs your mySaga.

And what mySaga will generates is an instruction for the middleware!

So from the previous example, takeLatest will generate an instruction.

What does this instruction says?

It says to wait for the latest dispatched action FETCH_ALL_USERS_DATA, and when that action is dispatched, initiate the specified worker saga.

You can build your watcher saga like this:

function* watcherSaga() {  
  yield takeLatest('ACTION_A', workerSagaA);
  yield takeLatest('ACTION_B', workerSagaB);...and so on
}

Redux Saga flow on sagaMiddleware.run(watcherSaga) call:

  1. watcherSaga is called.

  2. watcherSaga will returns an instruction for ACTION_A.

  3. middleware receive the instruction then continues to run watcherSaga.

  4. watcherSaga returns another instruction for ACTION_B.

  5. middleware receives the instruction then continues to run watcherSaga.

This whole process will stop whenever a blocking effect is reached, commonly known blocking effects are:

  • call

  • take

Call returns an instruction to the middleware to call the given function (which has to return a promise). The middleware will wait until the promise resolves and then continue to run the saga.

Take returns an instruction to the middleware to wait for a specific action before proceeding the saga.

What I was just elaborating what happens when sagaMiddleware.run(watcherSaga) is called, which in essence, just to provide as many instruction to the middleware.

You can deep more in the official documentation here: http://yelouafi.github.io/redux-saga/

Or even try yourself the library which you can find here: https://github.com/yelouafi/redux-saga

JavaScript for Noobs: Prototype using Function Constructor

As of my last post about prototypal inheritance, this post will go even further about the actual usage of prototype. On that last post I’ve discuss about how we can use proto  (underscore-underscore-proto-underscore-underscore) to access/mutate a JavaScript object.

On this post on the other hand, I’d like to discuss on how we suppose to use a function constructor.

If you haven’t checked on that last post, I suggest you to do so. Here’s the link to the previous series of prototypal inheritance.

function constructor and prototype

(Picture from Udemy’s course JavaScript: The Weird Parts)

Function, as you know, can functioned as a constructor, that is a special block of code that is invoked when you’re trying to create a new object using the new  operator.

There are no supplementary between a constructor and a normal function, they are just the same.

Although a constructor has the ability to access the newly created object, the constructor will be invoked using a pseudo parameter consisting a hidden reference of that newly created object. Afterwards, the reference is kept inside the this  keyword.

If you’re not familiar with function acting as a constructor, let me explain it a bit. The common method of using a function constructor is:

var obj = new randomFunction(param1, param2);  

new  is an operator, and in JavaScript operators are function. The new  keyword takes a certain parameters new … ([ … , … ]) .

When the JavaScript engine reads the keyword, it will create an entirely new object, and invoked the function constructor you provide along with the reference of that new object.

As long as the function constructor doesn’t have it’s own return expression, the JavaScript engine will automatically return the new object reference upon the entire new  expression.

Now.

When a function act as a constructor, and a *new  expression works upon him, then the prototype property (object) will live. *

It’s funny how the prototype for the function actually not the prototype for the function, it’s the prototype for the object that is created using that function constructor.

Prototype is useful so that any object that is created with the same function, sometime later we can add features to all of those objects at once by using this .prototype  property of the function constructor.

function randomFunction(firstName, lastName) {  
    this.firstName = firstName;
    this.lastName = lastName;
}
var randomObj = new randomFunction("Elon", "Musk");  
randomFunction.property.middleName = "John";  

The this keyword on a prototype will refers to the caller object.

randomFunction.property.randomProp = this.firstName + " " + this.lastNameasdasdasdsadasdasdasdas  
console.log(randomObj.randomProp);  

It will output “Elon Musk”.

For efficiency, put all methods inside the prototype, properties sometimes have different value thus not included in the prototype. Here’s what I’m talking about:

randomFunction.property.randomFunction = function(val) { return val; } var output = randomObj.randomFunction("Hello!"); console.log(output); // outputs Hello!

JavaScript for Noobs: What the heck is __proto__?

Prototypal inheritance is one component that gets acquaintance in JavaScript. You probably familiar with the classic inheritance which is wildly use among other programming languages, for instance: Java and C++.

Well, although prototypal inheritance is slightly similar with classic inheritance, but in fact, it is so much simple. In my opinion, though classic inheritance provides a decent structure for the code, but even a non-programmers can clearly notice it’s verbosity.

The concept of prototypal inheritance is pretty much easy to digest. Tip: keep it simple, don’t overthink it. Every object (except for a base object, we’ll cover it later) in JavaScript have this so-called prototype object as their properties. It consist of built-in properties/methods.

Here’s the thing: if you try to access a properties/method of an object and JavaScript engine doesn’t finds one, then it will search through it’s prototype object.

A prototype object may links to another prototype object. The only object that doesn’t refers to another prototype is a base object, and that said, is the bottom of the prototype chain.

There are several methods you could you use to mutate the prototype object, let’s deliberate one scheme that is not recommended due to performance issue. The following method will only make your code slow! But we’ll cover it for demo purposes.

Using proto

You can access an object’s prototype through proto  (dash-dash-proto-dash-dash). Remember to never ever everrr use this method.

proto  is available to all objects: object literals, functions, and even arrays. Let’s examine each, shall we.

Object Literals

The following is the proto  result when for an object literals, I have declared variable *a * previously as an object literals: var a = {};

object literal prototype

As you can see the prototype of the variable a  is an object. In this case, it’s a base object, that means it’s the end the prototype chain, there won’t be any other prototype object inside of this prototype.

Function

Here’s the result when you try to access it’s prototype:

function prototype

Hmm, interestingly, it’s an empty function. I’m not really sure about the idea around this, but as you know, function is literally an object too, hence there won’t be much difference whether the result is an Object {}  or a function Empty() {} .

You might wanna see what actually lies inside the prototype object, in this case, the first prototype object of the any function.

function prototype 2

Are you surprised? You might want to glimpse on methods like apply() , bind(),  and call() . You probably have used those methods several times, and yet you can’t figure why they’ re available to all functions out there. Well now you know, it’s there accessible thanks to JavaScript engine which discreetly put it under the hood, for you.

Now, I’d like to show you the base object of function objects:

function prototype base object

There you go!

Another proto  prototype lies inside the first proto  property. And, it’s an object, so as you might guess, it’s a base object, end of the prototype chain.

Array

Similar to function, but differs in the first proto  object:

array object prototype

Note that I’ve declared variable c*  *right before the statement. It appears that the proto  of an array is an array object as well. But, likewise a function, arrays are objects. Let’s just treat them the same.

Take a look at the built-in method/properties of it’s prototype object:

array object built-in

Yeah, push() , pop() , reduce() , and all other fancy methods come into sight. It’s kinda astonishing to discover their hideout.

On the next post I’ll discuss how to put prototype into real play. Just bear in mind that the proto  we conferred foregone is intended for nothing but awareness.