jsrosetta

Collections

Object

Node.js object literals and methods compared to structs/classes with separate methods in Go, Rust, Swift, and Java.

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

A Node.js object literal bundles data and methods into the same value. Go splits the two: a struct holds only data, and behavior is attached with functions that take a receiver (usually a pointer to that struct) declared elsewhere. Of these five languages, only Rust splits it the same way as Go: fields live in the struct, and methods live in a separate impl block. Swift is different — methods are written right inside the struct body, alongside the properties, much like how Java bundles fields and methods inside a class body; Swift's only real difference from Java is that it auto-generates a default constructor (a memberwise initializer), so there's nothing to hand-write. Java is closer to the JS object literal: a class bundles both fields and methods, just with explicit types.

An object literal with a property and a method

const obj = {
  someProperties: {
    foo: 'bar'
  },
  someMethod: (prop) => {
    return obj.someProperties[prop]
  }
}
 
let item = obj.someProperties['foo']
console.log(item) // bar
 
item = obj.someMethod('foo')
console.log(item) // bar

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