jsrosetta

Functions

First-Class Functions

First-class functions, closures, and currying in Node.js compared to function values and closures in Go, Rust, Swift, and Java.

Minimum versions
Node.js ≥ 12.20Go ≥ 1.0Rust ≥ 1.26Swift ≥ 2.0Java ≥ 25
Verified on
Node.js 24.12.0Go 1.27.1Rust 1.98.1Swift 6.2.4Java 25.0.4.1

Node.js code is an ES module: save it as .mjs or set "type": "module" in package.json.

In Node.js, functions are first-class values: you can assign them to variables, pass them as arguments, return them from other functions, and compose new ones out of old ones. Go treats functions as values too — the difference is that every function type must be declared explicitly, and there's no bind; closures handle that instead. Rust and Swift also treat functions as first-class values with closures, just like Go. Java wraps functions in functional interfaces (Function, BinaryOperator, Supplier, and so on) from the java.util.function package, and any variable captured by a closure must be "effectively final" — never reassigned after it's declared.

Assigning and passing functions

// assign a function to a variable
const add = (a, b) => a + b;
 
// pass a function as an argument (higher-order function)
const apply = (fn, a, b) => fn(a, b);
console.log(apply(add, 2, 3)); // 5

Closures: a function that remembers its own state

function makeCounter() {
  let count = 0;
  return () => ++count;
}
 
const counter = makeCounter();
console.log(counter(), counter(), counter()); // 1 2 3

Currying / partial application

const addTen = add.bind(null, 10);
console.log(addTen(5)); // 15

Reference: github.com/miguelmota/golang-for-nodejs-developers#first-class-functions