javascriptumlclosuressequence-diagramdiagrams

Diagrams for JavaScript functions


What tools can be used to convey concepts like JavaScript variable scoping and closures clearly in something similar to UML sequence diagrams? For example, how can code like the following: (the Infamous Loop Problem)

var arr = [];
for(var i=0; i<10; i++) {
    arr.push(function() { alert(i); });
}
for(var j=arr.length;j--;) {
    arr[j]();
}

... be clearly explained in a diagram similar to this one:

A blank UML sequence diagram


Solution

  • The code is an arbitrary example. The code has nothing to do with the question, merely demonstrates often misleading code which could benefit from being described.

    You can not describe closures and scoping in UML. There is simply no support for it, not in sequence diagrams anyway. Closures in JavaScript is a bit like defining a class in Java or C#, you don't put that in your UML. Hmm, I can't explain this very well ..

    Closures is something you have to inherently understand as a JavaScript programmer.

    What your UML should be focusing on are the entities and their interaction. Not some language 'quirk' (if you will) like the need for closures.

    I am all for describing misleading code, but a UML diagram is not the place for it. Put it in the comments in the source code. If anyone wants to know how this function works he'll look at the source code. If he doesn't want to know, don't bother him with it.