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.

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
| Go | JavaScript | Notes |
|---|---|---|
struct | Object, or class | Objects are reference values |
[]T slice | Array | Resizable, mixed contents, no types |
map[K]V | Map, or Object | Map keeps insertion order |
interface | None | Duck typing; TypeScript adds interfaces |
error return value | throw and try/catch | Or return a result by convention |
defer | finally, or using | |
| goroutine | async function, promise | One thread |
| channel | Async iterator, stream, queue | No built-in channel type |
context.Context | AbortSignal | |
sync.WaitGroup | Promise.all() | |
nil | null and undefined | Two values |
Values are copied in Go and shared in JavaScript
This is the difference that causes the most bugs for Go developers.
type Point struct{ X int }
a := Point{X: 1}
b := a
b.X = 2
fmt.Println(a.X, b.X)1 2const 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);2 2 true
2 3
0In 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.
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
}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);42
parse "x1": not a number
7 null bad input: sevenThe 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.
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);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.
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()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);[ 'worker 1', 'worker 2', 'worker 3' ]
worker 3Promise.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.
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()));received 1
received 2
received 3
sum 6The 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
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);timed out
fast
true TimeoutErrorA 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
s := "héllo😀"
fmt.Println(len(s), utf8.RuneCountInString(s))10 6const 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(" "));7 6
10
68 e9 6c 6c 6f 1f600Go'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
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));[ '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.
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);
}woof beep
TypeErrorAny 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
function readConfig() {
console.log("open");
try {
console.log("read");
return "config";
} finally {
console.log("close");
}
}
console.log(readConfig());open
read
close
configA 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.


