The Design of Code: Organizing JavaScript

by Anthony Colangelo

31 Reader Comments

Back to the Article
  1. Great article, and very relevant to what I’m doing at the moment. ALA has this amazing knack for posting an article at exactly the right time for me to incorporate its message into my development!

    Copy & paste the code below to embed this comment.
  2. Well done, sir. Right in line with my re-read (and more attentive read) of the Clean Code stuff. Also, nice job on the plugin!

    Copy & paste the code below to embed this comment.
  3. Great article, but I’m surprised that you didn’t touch on using the jQueryUI widget factory.

    Copy & paste the code below to embed this comment.
  4. This article feels more like a “$ is the new global” than about organizing JS in general.

    Copy & paste the code below to embed this comment.
  5. I’m concerned that redefining the “jpm” variable for every invokation of $.jPanelMenu adversely affects the scalability of this approach.

    Copy & paste the code below to embed this comment.
  6. Andrew: That’s awesome to hear, glad it could come in handy!

    Copy & paste the code below to embed this comment.
  7. Dan: The jQuery UI widget factory can certainly come in handy, but this approach is more targeted towards things that break the typical bounds of jQuery UI widgets.

    Copy & paste the code below to embed this comment.
  8. Nate: Are you concerned about the local scope within the plugin, or within the implementation code?

    Copy & paste the code below to embed this comment.
  9. What about:
    var jpm = (function () {
      method1 = function() {…}
      method2 = function () {…}
      method3 = function () { //here you can compose a toggle function from method1 and method2 }
      return {method1: method1, method2: method2, method3: method3};
    })();

    Is that a good pattern ?

    Copy & paste the code below to embed this comment.
  10. Hey.
    Great article.

    I have a few points I wanna share with you. First: the ‘this’ scope mess.

    If you have:

    var me = {
        methodA: function() {…},
        methodB: function() {
          this.methodA();
        }
    }

    Sometimes ‘this’ will not be pointing to ‘me’ but ‘window’ or whatever the call starts from. So i use ‘me.methodA()’ instead.

    Thinking like that, i usually write:

    me.methodA = function() {};
    me.methodB = function() {
        me.methodA();
    }

    return me;

    And when i dont wanna use jQuery as a global enviroment, i use a global object like a ‘java package’ of my code, normally the name of my company.

    Something like…

    // begging of my class file:
    if (typeof myCompany == ‘undefined’) {
        myCompany = {};
    }

    myCompany.MyClassName = function() {
      var me = {};
      me.methodA = function() {}
      return me;
    }
    // end of my classfile

    And usage like

    var a = new myCompany.MyClassName();
    a.methodA();

    I dont know if this is the best approach, but helps me a lot.

    Copy & paste the code below to embed this comment.
  11. Thank you for a nice, clearly written article – as a back-end dev slowly picking up the ropes of javascript, I really find simple explanations like this very helpful

    Copy & paste the code below to embed this comment.
  12. It seems that your jpm plugin is initialized only once on a page. Now, what if my jquery plugin could be instantiated multiple times on the same page. How would you modify the above code to accommodate that?
    Thanks for the great article by the way.

    Copy & paste the code below to embed this comment.
  13. Gabriel: That’s a great pattern, and is one of the reasons I love the module pattern so much. Being able to map API functions to those within the module is so nice!

    Copy & paste the code below to embed this comment.
  14. Pedro: Definitely great tips to share there. “This” does get somewhat confusing in more complex modules, so in those cases it’s great to switch over to the more specific usage of variable names. Good stuff to keep in mind!

    Copy & paste the code below to embed this comment.
  15. Oliver: To instantiate it multiple times, I’d just change the variable name that instances are saved to:

    var jpm = $.jPanelMenu( );
    var otherInstance = $.jPanelMenu( );

    And so on from there. Hope that helps!

    Copy & paste the code below to embed this comment.
  16. Obviously modules are the way to go in terms of writing your code, but they don’t solve the issue of having your dependencies managed which is also an important part of your js code management.

    Copy & paste the code below to embed this comment.
  17. Great article indeed. Module pattern is good, but I think that Revealing Module Pattern is even better. It allows defining private variables and methods. You keep your internal module’s logic hidden. Don’t you think so?

    Copy & paste the code below to embed this comment.
  18. Great article. I think the fact that JavaScript is so easy to pick up leads to a lot of bad code which actually kind of works unless you need to maintain it and change it regularly. Such patterns and article will hopefully help people learning that even though it’s easy to write unclean code in JavaScript, it’s easy to write clean code provided you use such patterns.

    Copy & paste the code below to embed this comment.
  19. Great article Anthony! I already used the module pattern to help organize my code, but this really helped with better understanding the implementation of options and creating an API to use. Thanks!

    Copy & paste the code below to embed this comment.
  20. As Nate Whittaker already pointed out, your approach of creating the whole “instance” from scratch every time you use the plugin could be optimized. I’d dismiss it as nitpicking, were it not for the fact, that your article is about code reuse among other things. Any serious discussion about code reusability should IMO include at least a mention of JavaScript’s prototypal inheritance and how to utilize it to create reusable code.

    Coincidentally, your #snippet6 has a scope bug in it. The “function mapping” you specifically mention before that snippet is a broken pattern, because just passing the functions doesn’t preserve their scope (and you use the scope and specifically mention it above). An easy solution (apart from using ‘me’) is to work with real constructors and create instances. Like:

    (function ($) {
          var PanelMenu = function (options) {
                  this.options = $.extend({
                        /* defaults */
                  }, options);
          };
          $.extend(PanelMenu.prototype, {
                  open: …
                  …
          });
          $.jPanelMenu = function (options) {
                  return new PanelMenu(options);
          };
          $.jPanelMenu.klass = PanelMenu;
    )(jQuery);

    As a bonus, I exposed the class constructor for easy extensibility.

    Copy & paste the code below to embed this comment.
  21. Why don’t you use $.fn.jPanelMenu = function(){….}; ?

    Copy & paste the code below to embed this comment.
  22. Great read. The thinking modularly and decoupling assets is crucial in creating code that is easy to maintain and re-use.

    Copy & paste the code below to embed this comment.
  23. Very easy to apply this code. Thanks for sharing!

    Copy & paste the code below to embed this comment.
  24. I agree with both Lars and hon2a.

    Also I wanted to say that when you keep a private more complex version of a method and only expose a simple API you are using the Facade pattern. I think you could mention it in #snippet 16 (witch as mention above has a scope bug).

    Copy & paste the code below to embed this comment.
  25. Great article, I’ve often turned to the module/revealing module pattern to organise my JS.  It’s simple,  just works and my colleagues can run with code changes without too much back and forth to me.  On thing about your article though, link to your github account doesn’t appear to work?!

    Copy & paste the code below to embed this comment.
  26. +1 for the article :)

    Copy & paste the code below to embed this comment.
  27. Thank you for your nice article. As web developers, we learnt from the API section that we can create the Javascript “Facade pattern” to encapsulate some functions that should not be visible to the caller. This is definitely a good pattern. The structure is clearer, I like that. It is a headache to have many “public” functions in Javascript, and very easy to get them mixed up and confused. This will help us keep the website development code organised and efficient.

    Copy & paste the code below to embed this comment.
  28. If you think Clifford`s story is shocking…, last week my brother’s mom in law also recieved a check for $9648 working 10 hours a week from their apartment and they’re classmate’s step-aunt`s neighbour was doing this for 4 months and recieved a check for over $9648 parttime on their computer. applie the guidelines here, http://m3mi.com/3621CHECK IT OUT

    Copy & paste the code below to embed this comment.
  29. Excellent article, this is exactly what I was looking for. Thanks!

    Copy & paste the code below to embed this comment.
  30. Copy & paste the code below to embed this comment.
  31. Great article! Two questions:

    1) what is the suggested way to declare private variables when using this pattern?

    2) why did you put openMenu(), closeMenu(), etc methods inside the jpm object? Why not leave them outside (making them accessible through the public methods by using ‘openMenu()’ instead of ‘jpm.openMenu()’, for example)? Does it make a difference?

    Copy & paste the code below to embed this comment.