Skip to content
jshacks.dev
Fundamentals

JavaScript for Go Developers a Practical Comparison

A guide for Go developers learning JavaScript: reference semantics, exceptions for errors, no zero values, and promises in place of goroutines and channels.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, npm, Vite and Node.js logos.

Go developers tend to find JavaScript's syntax easy and its behavior unsettling. The two languages sit at opposite ends of a spectrum: Go is statically typed, compiled, strict about unused variables, explicit about errors and built around goroutines, while JavaScript is dynamically typed, interpreted by an engine, lenient to the point of surprise, and built around a single thread with an event loop. A Go programmer's instincts are good ones, explicit error handling, small functions, composition over inheritance, and most of them transfer. The things that fail are the assumptions that came for free in Go: that values are copied, that a variable has a type and a zero value, that a function that can fail says so in its signature. This post goes through the differences with the output of each snippet, and ends with habits to build. The JavaScript runs on Node.js 24, and the Go is Go 1.23, with outputs written from the language rules.

The vocabulary map

GoJavaScriptNotes
structObject, or classObjects are reference values
[]T sliceArrayResizable, mixed contents, no types
map[K]VMap, or ObjectMap keeps insertion order
interfaceNoneDuck typing; TypeScript adds interfaces
error return valuethrow and try/catchOr return a result by convention
deferfinally, or using
goroutineasync function, promiseOne thread
channelAsync iterator, stream, queueNo built-in channel type
context.ContextAbortSignal
sync.WaitGroupPromise.all()
nilnull and undefinedTwo values

Values are copied in Go and shared in JavaScript

This is the difference that causes the most bugs for Go developers.

go
type Point struct{ X int }

a := Point{X: 1}
b := a
b.X = 2
fmt.Println(a.X, b.X)
Text
1 2
JavaScript
const a = { x: 1 };
const b = a;
b.x = 2;
console.log(a.x, b.x, a === b);

const c = { ...a };
c.x = 3;
console.log(a.x, c.x);

function reset(point) {
  point.x = 0;
}

reset(a);
console.log(a.x);
Text
2 2 true
2 3
0

In Go, assigning a struct copies it, and passing one to a function copies it too, unless you pass a pointer. In JavaScript, objects and arrays are always references: b = a gives a second name for one object, and a function that receives an object can change the caller's data. Primitives, which are numbers, strings, booleans, null, undefined, symbols and bigints, are copied by value. Make a copy with spread, which is shallow, or structuredClone(), which is deep. Every function that takes an object is, in effect, taking a pointer.

Errors: exceptions instead of returned values

Go functions return an error as a value, and callers check it. JavaScript functions throw, and callers catch.

go
func parse(s string) (int, error) {
    n, err := strconv.Atoi(s)
    if err != nil {
        return 0, fmt.Errorf("parse %q: %w", s, err)
    }
    return n, nil
}
JavaScript
function parse(text) {
  const value = Number(text);
  if (text.trim() === "" || Number.isNaN(value)) {
    throw new Error(`parse "${text}": not a number`);
  }
  return value;
}

for (const input of ["42", "x1"]) {
  try {
    console.log(parse(input));
  } catch (error) {
    console.log(error.message);
  }
}

function parseResult(text) {
  const value = Number(text);
  return Number.isNaN(value) ? [null, new Error(`bad input: ${text}`)] : [value, null];
}

const [value, error] = parseResult("7");
const [, failure] = parseResult("seven");
console.log(value, error, failure.message);
Text
42
parse "x1": not a number
7 null bad input: seven

The idiomatic JavaScript way is to throw, and nothing in a function's signature says it might. Callers that forget to catch crash the program, or the promise rejects, so documentation and tests carry the weight that Go's signature carries. A returned pair, destructured as [value, error], is possible and unusual, and is used for functions where failure is common and expected. Wrapping an error, Go's %w, is the cause option: new Error("load config", { cause: original }). Always throw Error objects, not strings, so a stack trace is attached.

No zero values

A Go variable always has a value: 0, "", false or nil. A JavaScript variable declared without a value is undefined, and a missing property is undefined too.

JavaScript
let count;
const user = { name: "Ada" };

console.log(count, user.age, user.age + 1);
console.log(typeof count, typeof user.age);

const counts = {};
const words = ["a", "b", "a"];

for (const word of words) {
  counts[word] = (counts[word] ?? 0) + 1;
}

console.log(counts);

const tally = new Map();
for (const word of words) tally.set(word, (tally.get(word) ?? 0) + 1);
console.log(tally);
Text
undefined undefined NaN
undefined undefined
{ a: 2, b: 1 }
Map(2) { 'a' => 2, 'b' => 1 }

counts[word]++ works in Go because a missing key reads as the zero value, 0. In JavaScript, a missing key is undefined, and undefined + 1 is NaN, so you supply the default with ??. There is no error for reading a missing property, so a typo in a property name returns undefined and the program carries on. A type checker, TypeScript, and a linter are the answer to the safety that the Go compiler gave you.

Goroutines and channels versus promises

JavaScript has one thread. There is no go keyword, and concurrency comes from asynchronous I/O and promises.

go
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
    wg.Add(1)
    go func(id int) { defer wg.Done(); work(id) }(i)
}
wg.Wait()
JavaScript
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));

async function work(id) {
  return delay(30 - id * 10, `worker ${id}`);
}

const results = await Promise.all([1, 2, 3].map(work));
console.log(results);

const first = await Promise.race([work(1), work(2), work(3)]);
console.log(first);
Text
[ 'worker 1', 'worker 2', 'worker 3' ]
worker 3

Promise.all plays the role of a wait group and returns results in input order, whatever order the work finished in. Promise.race returns the first to finish. These tasks wait, and do not run in parallel: a JavaScript program uses one thread, so CPU-heavy work blocks everything and needs a worker thread. For I/O-bound work, which is most server code, the model is efficient, and there are no data races on ordinary variables, so no mutex.

A channel replaced by an async iterator

Go code that passes values between goroutines on a channel maps to an async generator consumed with for await.

JavaScript
async function* produce() {
  for (let i = 1; i <= 3; i++) {
    await delay(5);
    yield i;
  }
}

async function consume(source) {
  let sum = 0;
  for await (const value of source) {
    console.log("received", value);
    sum += value;
  }
  return sum;
}

console.log("sum", await consume(produce()));
Text
received 1
received 2
received 3
sum 6

The producer yields values as they become ready, and the consumer waits for each one. This is a one-to-one pipeline without buffering. For many producers or consumers, or backpressure, Node.js streams are the closest tool. There is no select statement, so waiting for several sources combines Promise.race with the sources.

Timeouts and cancellation

JavaScript
function withTimeout(promise, ms) {
  return Promise.race([
    promise,
    new Promise((_, reject) => setTimeout(() => reject(new Error("timed out")), ms)),
  ]);
}

try {
  await withTimeout(delay(50, "slow"), 10);
} catch (error) {
  console.log(error.message);
}

console.log(await withTimeout(delay(5, "fast"), 50));

const signal = AbortSignal.timeout(10);
await delay(30);
console.log(signal.aborted, signal.reason.name);
Text
timed out
fast
true TimeoutError

A race with a timer is the equivalent of a select with time.After. For cancellation, pass an AbortSignal to the operations that support it, such as fetch, in the place of a context.Context. The timer in withTimeout does not cancel the slow work, only stops waiting for it, which is the same as in Go when you ignore a goroutine.

Strings: UTF-16, not UTF-8 bytes

go
s := "héllo😀"
fmt.Println(len(s), utf8.RuneCountInString(s))
Text
10 6
JavaScript
const text = "héllo😀";
console.log(text.length, [...text].length);
console.log(new TextEncoder().encode(text).length);
console.log([...text].map((c) => c.codePointAt(0).toString(16)).join(" "));
Text
7 6
10
68 e9 6c 6c 6f 1f600

Go's len counts bytes of UTF-8, and JavaScript's length counts UTF-16 code units, so the emoji counts as two. Spreading a string iterates code points, which are Go's runes. To get the UTF-8 byte length, encode with TextEncoder. Neither counts what a reader sees as one character, for which Intl.Segmenter is the tool.

Maps and ordering

JavaScript
const ages = new Map([["ada", 36], ["grace", 45], ["linus", 28]]);

console.log([...ages.keys()]);
console.log([...ages].sort((a, b) => a[1] - b[1]).map(([name]) => name));

const object = { b: 1, a: 2 };
console.log(Object.keys(object));
Text
[ 'ada', 'grace', 'linus' ]
[ 'linus', 'ada', 'grace' ]
[ 'b', 'a' ]

Go randomizes map iteration order on purpose. A JavaScript Map iterates in insertion order, and so do plain objects, apart from integer-like keys, which sort first. Code can depend on this order, and sorting is still needed for any order other than insertion.

Interfaces and composition

Go interfaces are satisfied implicitly, and the compiler checks it. JavaScript does the same without the check.

JavaScript
const dog = { speak: () => "woof" };
const robot = { speak: () => "beep", battery: 80 };

function greet(speaker) {
  return speaker.speak();
}

console.log(greet(dog), greet(robot));

try {
  greet({ name: "mute" });
} catch (error) {
  console.log(error.name);
}
Text
woof beep
TypeError

Any object with a speak method works, as in Go. The difference is that the mismatch shows up at run time as a TypeError, where Go refuses to compile. Composition works as in Go, by placing objects inside objects, and class with extends is available and should be used sparingly. TypeScript interfaces restore the compile-time check.

Cleanup: defer, finally and using

JavaScript
function readConfig() {
  console.log("open");
  try {
    console.log("read");
    return "config";
  } finally {
    console.log("close");
  }
}

console.log(readConfig());
Text
open
read
close
config

A finally block runs when the function exits by any route, as a deferred call does, though it is attached to a block and not to the function. The newer using declaration is closer to defer: it disposes of a resource at the end of the scope, as described in JavaScript Symbol.dispose.

Habits to build

Treat every object as a reference and copy when you need to. Use const by default. Throw Error objects and catch where you can act. Add defaults with ??. Await every promise. Use TypeScript or JSDoc types, and a linter, to replace the compiler. Run Prettier as you ran gofmt. And keep CPU-heavy work off the main thread.

Where the Go comparison stops

The ecosystems differ: Go ships a rich standard library and tends toward few dependencies, while JavaScript projects often depend on hundreds of small packages. Go's static linking and single binary have no equivalent. Performance models differ too, since a goroutine is cheap and truly parallel, and JavaScript parallelism needs workers. The reference is in the MDN JavaScript guide and the Go documentation.

Taggedgo
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.