Implementing the Visitor Pattern using JavaScript for fun during this weekend.

According to GOF [1], visitor pattern is:

“Represent an operation to be performed on elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.”

There are three key components when using visitor pattern:

  1. Element hierarchy, and
  2. Visitors, and
  3. Clients that use element hierarchy and visitors.

In my implementation, I have:

  1. Element hierarchy. abstract employee, full time and part time concrete employees
  2. Visitors. totalAmountSalaryVisitor, totalAmountPartTimeVisitor, averageCompensationVisitor
  3. Clients. Creates employees, add visitors, and get the results.

JavaScript is very expressive. If you want to add a ‘accept’ function to the employees array, you just add it. You don’t need to use a wrapper or extension method like class-oriented languages.

var employees = [];
employees.accept = function(visitor) { 
  this.forEach(function(element) {

Adding ‘accept’ method to the abstract employee just as simple.

var employee = function(spec) {
  var that = {};
  that.firstName = spec.firstName || "*";
  that.lastName = spec.lastName || "*";
  that.age = spec.age || 0;
  that.employmentType = spec.employmentType || "Employee"; 
  that.accept = function(visitor) {
  return that;


JavaScript is also class-free. You can just create visitor anytime and in any shape you want as long as it has a ‘visit’ method.

var totalAmountSalaryVisitor = {
  total: 0,
  visit: function(fullTimeEmployee) { += fullTimeEmployee.salary || 0;

Compared to the similar implementation in C# [5], the JavaScript version is more nature and more expressive, requires much less lines of codes, and, most importantly, more fun!

Full source code: (You have to click the ‘Remix’ button on the right top corner to see the source code.)


  1. Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley.  ISBN  0-201-63361-2