Anonymous functions

Inline `fun(params) { ... }` expressions: no name required.

Use fun followed directly by (params) { body } anywhere an expression is expected. The result is a function value you can pass to another call, assign to a variable, or return.

Anonymous functions are closures: they capture variables from the scope where they are created, same as named functions.

This is especially handy for HTTP route handlers, callbacks, and middleware where defining a separate named function would be boilerplate.

Assign to a variable

Store an anonymous function in a variable and call it later.

Assign to a variable
var double = fun(x) {
  return x * 2;
};

print double(21);
output
42

Pass inline to another function

Hand a `fun(...) { }` expression directly as an argument.

Pass inline to another function
fun applyTwice(fn, value) {
  return fn(fn(value));
}

print applyTwice(fun(n) { return n + 1; }, 10);
output
12

HTTP handlers (common pattern)

Route handlers are often anonymous functions passed to `http::get` and friends.

server.rn
benutzen "http";

http::cors(true);

http::get("/", fun(req) {
  return http::response(200, "anonymous works!");
});

http::get("/test/:id", fun(req) {
  return http::response(200, "id: " + req.params.id);
});

http::listen(8080);

Closure over outer variable

The inner `fun` keeps access to `n` from `makeAdder` after it returns.

Closure over outer variable
fun makeAdder(n) {
  return fun(x) {
    return x + n;
  };
}

var add5 = makeAdder(5);
print add5(10);
output
15

Notes