jsrosetta

Functions

Swapping Variables

Swapping two variables with array destructuring in Node.js compared to destructuring assignment in Rust, the `swap` function in Swift, multiple assignment in Go, and a temporary variable in Java.

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

Node.js swaps two variables with array destructuring, no temporary variable needed. Go does the exact same thing with multiple assignment — also with no temporary variable. Rust has had destructuring assignment for tuples since 1.59 ((b, a) = (a, b)), the same idea. Swift ships a swap(&a, &b) function in its standard library. Java has no syntax for this at all — you still need a temporary variable.

Swapping two variables

let a = 'foo';
let b = 'bar';
 
console.log(a, b); // foo bar
 
[b, a] = [a, b];
 
console.log(a, b); // bar foo

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