jsrosetta

Basics

Variables and Constants

What const and let in Node.js correspond to in Go, Rust, Swift, and Java.

In JavaScript you're used to two keywords: const (can't be reassigned) and let (can be reassigned). Most other languages split the same two concepts, just with different names and defaults.

Basic declarations

const name = "neko"; // cannot be reassigned
let count = 0;       // can be reassigned
count += 1;
 
console.log(name, count);
Node.js Go Rust Swift Java
const const (compile-time values only) let let final
let var / := let mut var regular variable / var

Compile-time constants

const in JavaScript only blocks reassignment — the value itself can still be computed at runtime. Other languages usually have an extra kind of constant that's evaluated at compile time.

const MAX_USERS = 100;
const startedAt = Date.now(); // still valid: computed at runtime

Default values when unassigned

JavaScript gives you undefined. Go assigns a zero value based on the type. The other languages force you to assign a value before using it.

let title;
console.log(title); // undefined

const doesn't mean immutable

In JavaScript, const only locks the reference. The object inside can still be mutated. Other languages handle this very differently:

const user = { name: "neko" };
user.name = "tama"; // valid
Object.freeze(user); // to really lock it down, you need to freeze it

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