Lim H. Lim H. - 4 years ago 173
Javascript Question

Anonymous function declaration shorthand javascript

I'm wondering whether there is any way to shorten anonymous function declaration in JavaScript through the utilization of preprocessor/compiler like Google Closure. I figure it'd be quite neat for callbacks.

For example, normally I'd write a qunit test case this way:

test("Dummy test", function(){ ok( a == b );});

I'm looking for some Clojure-inspired syntax as followed:

test("Dummy test", #(ok a b));

Is it possible?

Answer Source

Without worrying about preprocessors or compilers, you could do the following which shortens the callback syntax. One thing with this is that the scope of "this" isn't dealt with...but for your use case I don't think that's important:

var ok = function(a,b) {
  return (a==b);

var f = function(func) {
  var args =, 1);

  return function() {
    return func.apply(undefined,args);

Here's your shorthand syntax
var callback = f(ok,10,10);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download