CodeLog

TOD - Object.freeze

TOD: Freezing Configuration Objects in JavaScript

In today’s tip, let’s talk about ensuring constant configurations remain truly constant. Consider this example:

const config = { url: "https://url.com" };

You might assume config is immutable, but it’s not! You can still modify its properties:

config.url = "https://new.url.com"; // Allowed!

To prevent modifications, a common approach is to use a function:

const config = () => ({ url: "https://url.com" });

Each call to config() returns a new object, which is better but still not ideal. Here’s the real tip:

const config = Object.freeze({ url: "https://url.com" });

Why Object.freeze()?

The Object.freeze() method ensures that:

  • No new properties can be added.
  • Existing properties cannot be removed or modified.
  • The object’s prototype remains unchanged.

MDN Docs on Object.freeze()

Extra Tip for TypeScript Users

If you’re using TypeScript, you can use const assertions to make TypeScript aware that the object is frozen:

const config = Object.freeze({ url: "https://url.com" }) as const;

TypeScript’s const assertions ensure:

  • Literal types don’t widen (e.g., “hello” won’t become string).
  • Object literals have readonly properties.
  • Array literals become readonly tuples.

TypeScript 3.4 Const Assertions

That’s it! Stay tuned for more JavaScript Tips of the Day!