GGistDev

Constants in JavaScript

const creates a block‑scoped binding that cannot be reassigned. It does not make the referenced object immutable.

const vs let

const x = 1
// x = 2  // TypeError: Assignment to constant variable.
let y = 2
y = 3

Object immutability

Use Object.freeze (shallow) or libraries for deep immutability. Frozen only prevents adding/removing/changing own properties (shallow).

const cfg = Object.freeze({ debug: false, nested: { on: true } })
// cfg.nested.on = false // still allowed (shallow freeze)

Deep freeze utility:

function deepFreeze(o) {
  Object.getOwnPropertyNames(o).forEach(k => {
    const v = o[k]
    if (v && typeof v === 'object') deepFreeze(v)
  })
  return Object.freeze(o)
}

as const (TypeScript note)

In TS, as const narrows to literal/readonly types (if using TS or JSDoc types).

const roles = ["user", "admin"] as const

Naming and organization

Use SCREAMING_SNAKE_CASE for module‑level constants; group related values and export from a config module.

export const API_URL = "https://api.example.com"
export const DEFAULT_TIMEOUT_MS = 5_000

Environment constants

Read from env (Node) or inject at build time (Vite/webpack define). Validate at startup.

const NODE_ENV = process.env.NODE_ENV ?? 'development'
if (!process.env.API_KEY) throw new Error('Missing API_KEY')

Summary

  • const prevents rebinding; use freeze (possibly deep) for immutability
  • Prefer module‑level constants, clear naming, and validated envs