Why Sand.js make your code more portable ? - piercus/sandjs GitHub Wiki

Global is evil

In JavaScript, global is evil, because your variable may corrupt each others, and because it make your files dependent of an outside scope.

Sandboxing help you manage global variable issue. Usualy JS Sandboxing looks like that :

(function(){
  //my code here 
})();

The helpers problem

Let take a (stupid) example, you have a code than run on your browser, with jQuery, you scoped it to avoid using globals :

(function(jQ){ 
  var ar = [1, 2, 3, 4];
  jQ.each(ar, function(i){ console.log(i); });
})($);

Now you want to execute the same code with nodejs. Are you willing to load jQuery in nodejs just to loop on an array ? I'm sure you don't.

Now let's say you wrote your code with sandjs.

sand.define("stupidModule", ["jQuery->jQ"], function(r) { 
  var ar = [1, 2, 3, 4];
  r.jQ.each(ar, function(i){ console.log(i); });
});

sand.require("stupidModule");

Just add a fake jQuery module and load it on node

sand.define("jQuery", function(r) {
  return { each : function(a,b){ a.forEach(b); } };
});

Note : I know it's not the better solution. When you use Sand.js the best things to do is to use atomic dependencies, and doing something like that would be much better :

sand.define("stupidModule", ["each"], function(r) { 
  var ar = [1, 2, 3, 4];
  r.each(ar, function(i){ console.log(i); });
});

sand.require("stupidModule");