SlideShare a Scribd company logo
JavaScript Design Patterns
JavaScript developers have several options for creating an
Object in JavaScript, from the Object() method to Object
literals to constructor functions, there are a lot of ways to get
the job done. This article will present a few choice Object
creation Patterns. Pros and cons of each pattern are also
listed.
Curated by : Gomes, Jijo
Why should we follow a specific design
pattern?
- It helps to create modular and functional code
- Unit testable/reusable code since entire programming
paradigm shift to client side
What is wrong here?
This is a javascript file with a bunch of
functions written. There is no proper
structure followed. There is a global
variable resultCtrl, which means it is
not only accessible from the script file
but anywhere from the code. Since
global variable can be accessed from
anywhere in the code, it is very
difficult to understand what changes
what and when? This code is:-
1. Difficult to understand.
2. Difficult to maintain.
3. Not re-usable.
So how can we make it more
structured? Let's see how can we re-
write this code using different design
patterns.
1. Prototype Pattern
The Prototype Pattern can be broken out into two main
sections including a constructor section and a prototype
section. Prototyping allows functions and properties to be
associated with objects. However, instead of each object
instance getting a copy of all functions/properties each time
an object is created, only one set of functions/properties
exists across all objects resulting in less memory
consumption. In other words, functions and properties are
defined once per prototype rather than once per object.
Let's see how it works.
How does it work?
One imporatant point in structuring a
JavaScript code is that use namespace
in your code . In this example, it uses a
namespace called myNameSpace (if it
is already defined it uses it otherwise it
creates a new). As you can see it has a
constuctor section where the member is
intitialized and prototype section where
the public methods are defined. Then it
creates a new instance of the Calculator
and uses the functions defined in it. You
can create N number of Calculator
objects through out your code. As
mentioned earlier it won't create
duplicate of functions with each of the
objects created, instead all objects
share the same method definitions like
in C# or other programming languages
so it uses less memory. This pattern is
used mainly to create JavaScript
libraries. End user can use the existing
functionalities or add new functionalities
or modify existing ones through
prototypes.
Old code New Code
What changed?
2. Module Pattern
In JavaScript programing language, functions can be used as a Module. Sometimes, it is required to create a
singleton object instead of creating instance of a class. Inside the module, the inner functions do have the static
scope with the other defined variables and functions.
Maximum applications written in JavaScript languages are singletons only. Hence, they all are written in Module
pattern.
A Module can be considered as a Singleton Class in C#. In a Module, all the variables defined are visible only in
the module. Methods in a module have scope and access to the shared private data and private methods. Hence,
these methods are also called as Privileged methods.
Therefore, by creating one anonymous function returns a set of privileged methods in a simple object literal format.
And because of the closure principle, those privileged methods have access to the inner methods and variables of
the anonymous function. We call it as a Module Pattern.
Privileged Method
In Module Pattern, you can write your private methods, private variables those you don’t want to expose to the
other world and at the same time you will be able to write public and privileged methods also. The great usefulness
of this pattern is that you can very well access your private methods and variables from your methods those are
called as Privileged Methods.
Closure
In order to learn Module Pattern, one must be aware of Closure principle. By using closure only modular pattern
becomes very useful and powerful. Closure principle says that any inner function inside a parent function has
scope to the other inner function and variables although after the parent function has returned. In Module Pattern,
Privileged methods have scope to the other private variables and methods of the module.
How does it work?
As you can see, there is no separate
constructor section and method definition
section like we have seen in Prototype
pattern.
Like mentioned previously, calculator object
is initialized through self execution of the
method body. That is, an anonymous
function is executed with 'eq' as parameter,
and the result of the function (in this case,
object literal after the return statement) is
stored in the calculator object.
Very important thing to note about Module
Pattern is that, Normally each time a new
object is created a new set of functions will
be created. In this case 5 objects will create
5 x 4 = 20 method definitions!. So it's not
friendly on memory usage. So, that is the
reason this pattern has a self executing
method definition like given in the example
which in turn implements the Singleton
concept.
What changed?
Old Code New Code
3. Revealing Module Pattern
Module Pattern and Revealing Module Pattern are conceptually same,
but differs in the way member functions are defined.
How does it work?
As you can see, how methods are defined
differs from Module Pattern. Method
definitions are given names through var and
the these variables are used in the return
statement rather than function definitions like
we have seen in Module Pattern. One
advantage of using Revealing Module
Pattern over Module Pattern is that we can
have private methods. In this example 'add'
method can be removed from the object
literal in the return statement so that the
object will expose only subtract, multiply and
divide methods. But these 3 methods can
access 'add' method.
What changed?
Old Code New Code
4. Revealing Prototype Pattern
Revealing Prototype Pattern is a combination of Prototype Pattern and
Revealing Module Pattern.
How does it work?
What are the other benefits?
We have done the POC for patientfinancial.js and it works
like charm.
Let’s all follow this pattern for better eco system.
What next?
Code will be unit testable(framework like jasmine etc can be
adoptable)
Code will be reusable
Clean html and js separation of concern
Reference:
Book – “JavaScript: The Good Parts” – Douglas Crockford
http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatt
ernsjavascript
http://peter.michaux.ca/articles/module-pattern-provides-no-privacy-at-least-not-in-
javascript-tm
http://blog.alexanderdickson.com/javascript-revealing-module-pattern
And
Framework that follow the patterns are a lot, few are here.
knockoutJS
AngularJS
Backbone.JS
Ember.JS
Many in github…

More Related Content

DOCX
25 java tough interview questions
PPTX
Factory Design Pattern
PDF
Design patterns
PPTX
Creational pattern
PDF
GOF Design pattern with java
PDF
Factory Design Pattern
PDF
Oops presentation java
PPT
Factory Method Design Pattern
25 java tough interview questions
Factory Design Pattern
Design patterns
Creational pattern
GOF Design pattern with java
Factory Design Pattern
Oops presentation java
Factory Method Design Pattern

What's hot (19)

PPTX
WHAT IS ABSTRACTION IN JAVA
PPTX
Factory Method Pattern
PPTX
Lecture 18
PDF
Inverting Dependencies
PDF
Javapolymorphism
PPTX
Factory method pattern
PPTX
Desing pattern prototype-Factory Method, Prototype and Builder
DOC
PDF
Factory method pattern (Virtual Constructor)
PPTX
Basic concept of class, method , command line-argument
PPTX
Composite design pattern
PPTX
Std 12 computer chapter 8 classes and object in java (part 2)
DOCX
C# interview quesions
PPT
Factory Method Pattern
PPTX
#OOP_D_ITS - 8th - Class Diagram
DOC
DOC
C# interview questions
PPTX
Oops in vb
PPTX
How to implement dependency injection in c#
WHAT IS ABSTRACTION IN JAVA
Factory Method Pattern
Lecture 18
Inverting Dependencies
Javapolymorphism
Factory method pattern
Desing pattern prototype-Factory Method, Prototype and Builder
Factory method pattern (Virtual Constructor)
Basic concept of class, method , command line-argument
Composite design pattern
Std 12 computer chapter 8 classes and object in java (part 2)
C# interview quesions
Factory Method Pattern
#OOP_D_ITS - 8th - Class Diagram
C# interview questions
Oops in vb
How to implement dependency injection in c#
Ad

Viewers also liked (6)

PDF
Intro to Python Workshop San Diego, CA (January 19, 2013)
PDF
Javascript Module Patterns
PDF
JavaScript Modules Done Right
PDF
JavaScript Patterns
PDF
Modern JavaScript Applications: Design Patterns
Intro to Python Workshop San Diego, CA (January 19, 2013)
Javascript Module Patterns
JavaScript Modules Done Right
JavaScript Patterns
Modern JavaScript Applications: Design Patterns
Ad

Similar to Javascript design patterns (20)

PDF
Design patterns in java script, jquery, angularjs
PPTX
Design pattern in an expressive language java script
PDF
"The JavaScript Design Patterns You have to Know" by Rashad Majali
PPT
Patterns In-Javascript
PDF
Design patterns in javascript
PPTX
Introduction to Design Patterns in Javascript
PPTX
Presenter deck icenium hol
PPT
Douglas Crockford Presentation Goodparts
PPT
Design pattern
PPTX
Patterns in JavaScript
PPTX
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
PDF
Javascript Design Patterns
PPT
Goodparts
PPT
Java Script Patterns
PDF
Scalable JavaScript Design Patterns
PDF
Introduction to JavaScript design patterns
PDF
Unleashing the Power of Modern Javascript Development
PPTX
Javascript Common Design Patterns
PDF
Javascript Design Patterns
PDF
Future-proofing Your JavaScript Apps (Compact edition)
Design patterns in java script, jquery, angularjs
Design pattern in an expressive language java script
"The JavaScript Design Patterns You have to Know" by Rashad Majali
Patterns In-Javascript
Design patterns in javascript
Introduction to Design Patterns in Javascript
Presenter deck icenium hol
Douglas Crockford Presentation Goodparts
Design pattern
Patterns in JavaScript
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
Javascript Design Patterns
Goodparts
Java Script Patterns
Scalable JavaScript Design Patterns
Introduction to JavaScript design patterns
Unleashing the Power of Modern Javascript Development
Javascript Common Design Patterns
Javascript Design Patterns
Future-proofing Your JavaScript Apps (Compact edition)

Recently uploaded (20)

PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Spectroscopy.pptx food analysis technology
PDF
Machine learning based COVID-19 study performance prediction
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Machine Learning_overview_presentation.pptx
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Cloud computing and distributed systems.
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
MYSQL Presentation for SQL database connectivity
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Electronic commerce courselecture one. Pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
Dropbox Q2 2025 Financial Results & Investor Presentation
Encapsulation_ Review paper, used for researhc scholars
Diabetes mellitus diagnosis method based random forest with bat algorithm
Spectroscopy.pptx food analysis technology
Machine learning based COVID-19 study performance prediction
Chapter 3 Spatial Domain Image Processing.pdf
Machine Learning_overview_presentation.pptx
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Review of recent advances in non-invasive hemoglobin estimation
A comparative analysis of optical character recognition models for extracting...
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Cloud computing and distributed systems.
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Unlocking AI with Model Context Protocol (MCP)
MYSQL Presentation for SQL database connectivity
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Empathic Computing: Creating Shared Understanding
Electronic commerce courselecture one. Pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?

Javascript design patterns

  • 1. JavaScript Design Patterns JavaScript developers have several options for creating an Object in JavaScript, from the Object() method to Object literals to constructor functions, there are a lot of ways to get the job done. This article will present a few choice Object creation Patterns. Pros and cons of each pattern are also listed. Curated by : Gomes, Jijo
  • 2. Why should we follow a specific design pattern? - It helps to create modular and functional code - Unit testable/reusable code since entire programming paradigm shift to client side
  • 3. What is wrong here? This is a javascript file with a bunch of functions written. There is no proper structure followed. There is a global variable resultCtrl, which means it is not only accessible from the script file but anywhere from the code. Since global variable can be accessed from anywhere in the code, it is very difficult to understand what changes what and when? This code is:- 1. Difficult to understand. 2. Difficult to maintain. 3. Not re-usable. So how can we make it more structured? Let's see how can we re- write this code using different design patterns.
  • 4. 1. Prototype Pattern The Prototype Pattern can be broken out into two main sections including a constructor section and a prototype section. Prototyping allows functions and properties to be associated with objects. However, instead of each object instance getting a copy of all functions/properties each time an object is created, only one set of functions/properties exists across all objects resulting in less memory consumption. In other words, functions and properties are defined once per prototype rather than once per object. Let's see how it works.
  • 5. How does it work? One imporatant point in structuring a JavaScript code is that use namespace in your code . In this example, it uses a namespace called myNameSpace (if it is already defined it uses it otherwise it creates a new). As you can see it has a constuctor section where the member is intitialized and prototype section where the public methods are defined. Then it creates a new instance of the Calculator and uses the functions defined in it. You can create N number of Calculator objects through out your code. As mentioned earlier it won't create duplicate of functions with each of the objects created, instead all objects share the same method definitions like in C# or other programming languages so it uses less memory. This pattern is used mainly to create JavaScript libraries. End user can use the existing functionalities or add new functionalities or modify existing ones through prototypes.
  • 6. Old code New Code What changed?
  • 7. 2. Module Pattern In JavaScript programing language, functions can be used as a Module. Sometimes, it is required to create a singleton object instead of creating instance of a class. Inside the module, the inner functions do have the static scope with the other defined variables and functions. Maximum applications written in JavaScript languages are singletons only. Hence, they all are written in Module pattern. A Module can be considered as a Singleton Class in C#. In a Module, all the variables defined are visible only in the module. Methods in a module have scope and access to the shared private data and private methods. Hence, these methods are also called as Privileged methods. Therefore, by creating one anonymous function returns a set of privileged methods in a simple object literal format. And because of the closure principle, those privileged methods have access to the inner methods and variables of the anonymous function. We call it as a Module Pattern. Privileged Method In Module Pattern, you can write your private methods, private variables those you don’t want to expose to the other world and at the same time you will be able to write public and privileged methods also. The great usefulness of this pattern is that you can very well access your private methods and variables from your methods those are called as Privileged Methods. Closure In order to learn Module Pattern, one must be aware of Closure principle. By using closure only modular pattern becomes very useful and powerful. Closure principle says that any inner function inside a parent function has scope to the other inner function and variables although after the parent function has returned. In Module Pattern, Privileged methods have scope to the other private variables and methods of the module.
  • 8. How does it work? As you can see, there is no separate constructor section and method definition section like we have seen in Prototype pattern. Like mentioned previously, calculator object is initialized through self execution of the method body. That is, an anonymous function is executed with 'eq' as parameter, and the result of the function (in this case, object literal after the return statement) is stored in the calculator object. Very important thing to note about Module Pattern is that, Normally each time a new object is created a new set of functions will be created. In this case 5 objects will create 5 x 4 = 20 method definitions!. So it's not friendly on memory usage. So, that is the reason this pattern has a self executing method definition like given in the example which in turn implements the Singleton concept.
  • 10. 3. Revealing Module Pattern Module Pattern and Revealing Module Pattern are conceptually same, but differs in the way member functions are defined.
  • 11. How does it work? As you can see, how methods are defined differs from Module Pattern. Method definitions are given names through var and the these variables are used in the return statement rather than function definitions like we have seen in Module Pattern. One advantage of using Revealing Module Pattern over Module Pattern is that we can have private methods. In this example 'add' method can be removed from the object literal in the return statement so that the object will expose only subtract, multiply and divide methods. But these 3 methods can access 'add' method.
  • 13. 4. Revealing Prototype Pattern Revealing Prototype Pattern is a combination of Prototype Pattern and Revealing Module Pattern.
  • 14. How does it work?
  • 15. What are the other benefits? We have done the POC for patientfinancial.js and it works like charm. Let’s all follow this pattern for better eco system. What next? Code will be unit testable(framework like jasmine etc can be adoptable) Code will be reusable Clean html and js separation of concern
  • 16. Reference: Book – “JavaScript: The Good Parts” – Douglas Crockford http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatt ernsjavascript http://peter.michaux.ca/articles/module-pattern-provides-no-privacy-at-least-not-in- javascript-tm http://blog.alexanderdickson.com/javascript-revealing-module-pattern And Framework that follow the patterns are a lot, few are here. knockoutJS AngularJS Backbone.JS Ember.JS Many in github…