Skip to main content

Constants & Enums

Constants and enumerations help create readable, maintainable code. Here's how different languages handle them.

Constants​

// const (block-scoped, not deeply immutable)
const PI = 3.14159;
const MAX_SIZE = 100;
const API_URL = "https://api.example.com";

// const objects can be mutated!
const config = { debug: true };
config.debug = false; // OK!

// Object.freeze (shallow immutable)
const frozen = Object.freeze({ a: 1, b: 2 });
// frozen.a = 3; // Silently fails (or error in strict)

// Deep freeze (recursive)
function deepFreeze(obj) {
Object.freeze(obj);
Object.values(obj).forEach(v => {
if (typeof v === 'object') deepFreeze(v);
});
return obj;
}

// Enum pattern (no native enums in JS)
const Status = Object.freeze({
ACTIVE: 'active',
INACTIVE: 'inactive',
BANNED: 'banned',
});

Key Takeaways​

  • True immutability -- Rust const, Zig const, and C++ constexpr provide compile-time constants that cannot be changed. JavaScript const only prevents reassignment: const obj = {}; obj.x = 1 is allowed. Python has no true constants; PI = 3.14 can be reassigned. Use Object.freeze() in JavaScript or typing.Final in Python for convention-based immutability, but these are not enforced as strongly as in Rust or Zig. For maximum safety, prefer languages with compiler-enforced constants.

  • Algebraic data types -- Rust and Swift enums can carry associated values, enabling sum types. For example, enum Shape { Circle(f64), Rectangle(f64, f64) } in Rust lets each variant hold data. Zig's tagged unions and Swift's enum Shape { case circle(radius: Double) } work similarly. This enables exhaustive pattern matching and avoids invalid states. When modeling state machines or variants with payloads, prefer Rust, Swift, or Zig over simple integer enums.

  • Enum capabilities by language -- Java and C# enums support methods and fields: enum Color { RED("#FF0000"); private String hex; Color(String h) { hex = h; } }. Go uses iota for integer enums: const (Red = iota; Green; Blue). C enums are plain integers with no type safety; they pollute the global namespace. PHP 8.1+ and Python's enum module provide first-class enums. When you need enums with behavior or type safety, prefer Java, C#, Rust, Swift, or Python; for simple flags, C or Go's iota may suffice.

  • Defining constants -- C uses #define for preprocessor constants; C++ adds const and constexpr. Java and C# use static final; Go uses const; Rust uses const (compile-time) or static (runtime, single instance). Python and Ruby rely on naming conventions (UPPER_CASE). For compile-time evaluation and inlining, prefer constexpr (C++) or const (Rust, Zig); for runtime constants that are computed once, use static in Rust or static readonly in C#.