Implementing Immutable Variables in JavaScript ES5 Using Object.defineProperty
While const in ES6 provides a straightforward way to declare constants, ES5 developers can achieve similar immutability using Object.defineProperty. This method allows property definition with configurable descriptors, controlling writability and other attributes.
Core Usage of Object.defineProperty
The Object.defineProperty(obj, prop, descriptor) function defines or modifies an object's property. It accepts three arguments:
obj: The target object.prop: The property name or Symbol.descriptor: An object specifying property attributes.
By default, the writable descriptor is false, preventing property reassignment.
var dataStore = {};
Object.defineProperty(dataStore, 'id', {
value: 'user_001'
});
console.log(dataStore.id); // Output: user_001
dataStore.id = 'user_002'; // Attempted reassignment
console.log(dataStore.id); // Output remains: user_001
Setting writable: true permits modification:
var config = {};
Object.defineProperty(config, 'mode', {
value: 'development',
writable: true
});
config.mode = 'production';
console.log(config.mode); // Output: production
Defining Global Constants
Attaching a property to the window object creates a globally accessible constant:
Object.defineProperty(window, 'APP_NAME', {
value: 'MyApplication'
});
console.log(APP_NAME); // Output: MyApplication
APP_NAME = 'RenamedApp'; // Ignored
window.APP_NAME = 'AnotherName'; // Ignored
console.log(APP_NAME); // Output: MyApplication
Limitations with Reference Types
When the value is a reference type (object, array), the property's reference remains constant, but the referenced object's contents can be altered:
Object.defineProperty(window, 'SETTINGS', {
value: { theme: 'light' }
});
SETTINGS.theme = 'dark'; // Modifies the object's property
console.log(SETTINGS); // Output: { theme: 'dark' }
// Reassignment attempts are still blocked
SETTINGS = { theme: 'blue' }; // Ignored
This occurs because the constant holds the memory address of the reference, not the referenced data itself.
Browser Comaptibility Considerations
Object.defineProperty is supported in IE9+ and all modern browsers, but earlier versions lack support. For broader compatibility, consider polyfills or alternative patterns in legacy environments.