JavaScript Patterns

There are some common patterns that we see in JavaScript code when we start working.Walk you
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 on below with illustrated examples:
# Functions as abstractions.
# Function to build Modules.
# Function to avoid global variables.
 
Functions as abstraction
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 of this function, and assign it to a variable called work.
Ex.

 

Output: working hard!
Next we will increase the level of abstraction and going to 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 doWork extending the previous function as below:

 

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. Example to demonstrate the scenario.We will create a variable
createWorker point to two tasks. As below:

 

Next we can call these functions whatever I want. Like below:

 

Here we are really 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 been seen so far, both this code and the previous
code snippet, is that we are creating global variables.
Next how to avoid them.
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 () {

})();

 
All the code 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s