jsrosetta

Collections

Map

Node.js's Map (set/get/has/delete, for...of) compared to Go's map[K]V, Rust's HashMap, Swift's Dictionary, and Java's HashMap.

Minimum versions
Node.js ≥ 12.20Go ≥ 1.23Rust ≥ 1.58Swift ≥ 3.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's Map is a dedicated class with set/get/has/delete methods. Go has map[K]V right in the language syntax, no class or methods needed — you access it with [], and check for existence with the second return value ("comma ok"). Rust has HashMap<K, V> in its standard library, Swift has Dictionary with [K: V] syntax, and Java has HashMap — none of the three preserve insertion order when iterated, just like Go.

set, get, has, delete

const map = new Map()
map.set('foo', 'bar')
 
let found = map.has('foo')
console.log(found) // true
 
let item = map.get('foo')
console.log(item) // bar
 
map.delete('foo')
 
found = map.has('foo')
console.log(found) // false
 
item = map.get('foo')
console.log(item) // undefined

Iterating over a map

const map3 = new Map()
map3.set('foo', 100)
map3.set('bar', 200)
map3.set('baz', 300)
 
for (const [key, value] of map3) {
  console.log(key, value)
}
// foo 100
// bar 200
// baz 300 (Map preserves insertion order)

Key differences

Node.js Map Go map[K]V Rust HashMap Swift Dictionary Java HashMap
Checking existence .has(key) value, ok := m[key] .contains_key(key) dict[key] != nil .containsKey(key)
Value when key is missing undefined the type's zero value ("", 0, …) None (an Option<&V>) nil (a V?) null
Iteration order preserves insertion order randomized not guaranteed not guaranteed not guaranteed
Deleting a key .delete(key) delete(m, key) .remove(key) .removeValue(forKey:) .remove(key)

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