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

What's hot (19)

PPTX
WHAT IS ABSTRACTION IN JAVA
sivasundari6
 
PPTX
Factory Method Pattern
Anjan Kumar Bollam
 
PPTX
Lecture 18
talha ijaz
 
PDF
Inverting Dependencies
Luc Trudeau
 
PDF
Javapolymorphism
karthikenlume
 
PPTX
Factory method pattern
Shahriar Iqbal Chowdhury
 
PPTX
Desing pattern prototype-Factory Method, Prototype and Builder
paramisoft
 
DOC
C#
LiquidHub
 
PDF
Factory method pattern (Virtual Constructor)
Sameer Rathoud
 
PPTX
Basic concept of class, method , command line-argument
Suresh Mohta
 
PPTX
Composite design pattern
MUHAMMAD FARHAN ASLAM
 
PPTX
Std 12 computer chapter 8 classes and object in java (part 2)
Nuzhat Memon
 
DOCX
C# interview quesions
Shashwat Shriparv
 
PPT
Factory Method Pattern
Juan Carlos Giraldo Cardozo
 
PPTX
#OOP_D_ITS - 8th - Class Diagram
Hadziq Fabroyir
 
DOC
Vvi
Laxman Nikam
 
DOC
C# interview questions
Chetan Chaudhari
 
PPTX
Oops in vb
Dalwin INDIA
 
PPTX
How to implement dependency injection in c#
Priyank Mittal
 
WHAT IS ABSTRACTION IN JAVA
sivasundari6
 
Factory Method Pattern
Anjan Kumar Bollam
 
Lecture 18
talha ijaz
 
Inverting Dependencies
Luc Trudeau
 
Javapolymorphism
karthikenlume
 
Factory method pattern
Shahriar Iqbal Chowdhury
 
Desing pattern prototype-Factory Method, Prototype and Builder
paramisoft
 
Factory method pattern (Virtual Constructor)
Sameer Rathoud
 
Basic concept of class, method , command line-argument
Suresh Mohta
 
Composite design pattern
MUHAMMAD FARHAN ASLAM
 
Std 12 computer chapter 8 classes and object in java (part 2)
Nuzhat Memon
 
C# interview quesions
Shashwat Shriparv
 
Factory Method Pattern
Juan Carlos Giraldo Cardozo
 
#OOP_D_ITS - 8th - Class Diagram
Hadziq Fabroyir
 
C# interview questions
Chetan Chaudhari
 
Oops in vb
Dalwin INDIA
 
How to implement dependency injection in c#
Priyank Mittal
 

Viewers also liked (6)

PDF
Intro to Python Workshop San Diego, CA (January 19, 2013)
Kendall
 
PDF
Javascript Module Patterns
Nicholas Jansma
 
PDF
JavaScript Modules Done Right
Mariusz Nowak
 
PDF
JavaScript Patterns
Stoyan Stefanov
 
PDF
Modern JavaScript Applications: Design Patterns
Volodymyr Voytyshyn
 
Intro to Python Workshop San Diego, CA (January 19, 2013)
Kendall
 
Javascript Module Patterns
Nicholas Jansma
 
JavaScript Modules Done Right
Mariusz Nowak
 
JavaScript Patterns
Stoyan Stefanov
 
Modern JavaScript Applications: Design Patterns
Volodymyr Voytyshyn
 
Ad

Similar to Javascript design patterns (20)

PPT
Patterns In-Javascript
Mindfire Solutions
 
PPTX
Javascript Object Patterns.pptx
Alaref Abushaala
 
PDF
4 pillars of OOPS CONCEPT
Ajay Chimmani
 
PDF
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Akhil Mittal
 
PPTX
Design pattern in an expressive language java script
Amit Thakkar
 
PPT
Jump Start To Ooad And Design Patterns
Lalit Kale
 
PPS
Jump start to OOP, OOAD, and Design Pattern
Nishith Shukla
 
PPTX
OOP interview questions & answers.
Questpond
 
PPTX
Mastering Python lesson 4_functions_parameters_arguments
Ruth Marvin
 
PPTX
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Luis Valencia
 
ODP
(An Extended) Beginners Guide to Object Orientation in PHP
Rick Ogden
 
PDF
Why Design Patterns Are Important In Software Engineering
Protelo, Inc.
 
PDF
Andy Bulka Pattern Automation
tcab22
 
ODP
Design Patterns
imedo.de
 
PPTX
jquery summit presentation for large scale javascript applications
DivyanshGupta922023
 
PPT
Refactoring Tips by Martin Fowler
Igor Crvenov
 
DOCX
Generic Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
PDF
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
PDF
Java Design Patterns Interview Questions PDF By ScholarHat
Scholarhat
 
PPT
Object Oriented Programming (Advanced )
ayesha420248
 
Patterns In-Javascript
Mindfire Solutions
 
Javascript Object Patterns.pptx
Alaref Abushaala
 
4 pillars of OOPS CONCEPT
Ajay Chimmani
 
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...
Akhil Mittal
 
Design pattern in an expressive language java script
Amit Thakkar
 
Jump Start To Ooad And Design Patterns
Lalit Kale
 
Jump start to OOP, OOAD, and Design Pattern
Nishith Shukla
 
OOP interview questions & answers.
Questpond
 
Mastering Python lesson 4_functions_parameters_arguments
Ruth Marvin
 
Typescript design patterns applied to sharepoint framework - Sharepoint Satur...
Luis Valencia
 
(An Extended) Beginners Guide to Object Orientation in PHP
Rick Ogden
 
Why Design Patterns Are Important In Software Engineering
Protelo, Inc.
 
Andy Bulka Pattern Automation
tcab22
 
Design Patterns
imedo.de
 
jquery summit presentation for large scale javascript applications
DivyanshGupta922023
 
Refactoring Tips by Martin Fowler
Igor Crvenov
 
Generic Repository Pattern in MVC3 Application with Entity Framework
Akhil Mittal
 
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
Java Design Patterns Interview Questions PDF By ScholarHat
Scholarhat
 
Object Oriented Programming (Advanced )
ayesha420248
 
Ad

Recently uploaded (20)

PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 

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…