jsrosetta

Functions

Default Values

Default parameters in Node.js and Swift compared to Option (Rust), overloading (Java), and pointers + nil (Go).

Minimum versions
Node.js ≥ 12.20Go ≥ 1.0Rust ≥ 1.0Swift ≥ 5.1Java ≥ 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.

Node.js lets you assign a default value right in the parameter list. Swift is the only other language here with that exact syntax. Go has no such syntax — to know whether the caller left a parameter blank, you use a pointer and check for nil. Rust has no default parameters either — it uses Option to force the caller to be explicit about "some value" vs. "none". Java solves it with overloading: define several versions of the same function.

Default parameter values

function greet(name = 'stranger') {
  return `hello ${name}`;
}
 
console.log(greet());      // hello stranger
console.log(greet('bob')); // hello bob

Reference: github.com/miguelmota/golang-for-nodejs-developers#default-values