JavaScript Coding Patterns

Introduction

 
There are some common patterns that we see in JavaScript code when we start working. I will walk through some of these common JavaScript coding patterns to show you how JavaScript can be used as a functional language and how we can use functions to create abstractions. Abstractions are useful because they typically provide some sort of encapsulation to make other code easier to write. 
 
We will be discussing the following with illustrated examples:
  • Functions as abstractions.
  • Function to build Modules.
  • Function to avoid global variables.

Functions as abstractions

  • In JavaScript, we have a variable pointing to a function.
  • We will create a variable called work and want that variable to immediately point to a function. The purpose of this function is to abstract away some sort of operation that needs to be performed. We need to do some work, we want to wrap all that work up inside this function, and assign it to a variable called a task.
For example
 
Figure 1: Task
 
Next, we will increase the level of abstraction and define a function that will execute some work. This is quite helpful in case you pass a function to do something on your behalf.
 
Let us create another variable called todo extending the previous function as in the following code snippet :
 
Figure 2: Todo
 

Function to build Modules

 
Functions are a useful abstraction in JavaScript, but sometimes we need more than just a function. Sometimes we need an object, and that object has data and it has methods attached to it, and that's the type of abstraction that we need. The following is an example to demonstrate the scenario. We will create a variable create task point to two tasks. Here's the snippet:
 
Figure 3: CreateTask
 
Next, we can call these functions whatever we want. Here's the snippet:
 
Figure 4: Snippet
 
Here we are defining the public API and saying here's an object that has two methods, job1 and job2, no one really needs to know what is inside.
 
**Now the one drawback to the code that we have seen so far, both his code and the previous code snippet is that we are creating global variables.
 
Next we will see how to avoid global variables.
 

Function to avoid global variables

  • If you've been doing software development for any time, you've probably heard that global variables are bad. They easily become a source of confusion and bugs.
  • To avoid this we will use Immediately Invoked Function Expression (IIFE).
Syntax
 
( function() { ………….} () );
 

Summary

 
All the code is wrapped inside one function called IIFE. A lot of libraries use IIFEs to control the scope of the variables to build modules to provide encapsulation, and most of all to avoid those global variables.