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 foopackage main
import "fmt"
func main() {
a := "foo"
b := "bar"
fmt.Println(a, b) // foo bar
b, a = a, b
fmt.Println(a, b) // bar foo
}fn main() {
let mut a = "foo";
let mut b = "bar";
println!("{a} {b}"); // foo bar
(b, a) = (a, b); // destructuring assignment, no `let` needed
println!("{a} {b}"); // bar foo
}var a = "foo"
var b = "bar"
print(a, b) // foo bar
swap(&a, &b) // swap ships in the standard library
print(a, b) // bar foovoid main() {
String a = "foo";
String b = "bar";
IO.println(a + " " + b); // foo bar
// no destructuring assignment: still needs a temporary variable
String temp = a;
a = b;
b = temp;
IO.println(a + " " + b); // bar foo
}Reference: github.com/miguelmota/golang-for-nodejs-developers#swapping