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:
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
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.