Blog>
Snippets

Immutable Object Patterns with Object.freeze and Object.defineProperty

Ensure object properties cannot be changed by combining Object.freeze with non-writable properties defined through Object.defineProperty.
// Define an object with a non-writable property
const myObject = {};
Object.defineProperty(myObject, 'immutableProperty', {
  value: 'This property is immutable',
  writable: false, // Prevents the property from being overwritten
  configurable: false // Prevents the property from being redefined or deleted
});

// Freeze the entire object to prevent adding new properties
Object.freeze(myObject);
Creates an object with a non-writable property using Object.defineProperty and then freezes the object with Object.freeze to ensure its properties cannot be changed or new properties added.