Use Object.freeze() to make objects immutable
const config = Object.freeze({
apiUrl: 'https://api.example.com',
timeout: 5000
});
config.timeout = 3000; // Fails silently (or throws in strict mode)
console.log(config.timeout); // 5000const constants = Object.freeze({
PI: 3.14159,
MAX_SIZE: 100,
STATUS: Object.freeze({
PENDING: 'pending',
COMPLETE: 'complete'
})
});
// Attempts to modify will fail
constants.PI = 3.14; // No effect
constants.NEW_PROP = 'value'; // No effect
console.log(constants.PI); // 3.14159
// Deep freeze function
function deepFreeze(obj) {
Object.freeze(obj);
Object.values(obj).forEach(value => {
if (typeof value === 'object' && value !== null) {
deepFreeze(value);
}
});
return obj;
}const sealed = Object.seal(obj);
// Can modify existing props, can't add/deleteconst isFrozen = Object.isFrozen(obj);
const isSealed = Object.isSealed(obj);Avoid thinking freeze is deep by default
// DON'T DO THIS
const obj = Object.freeze({ nested: { val: 1 } });
obj.nested.val = 2; // This WILL work - freeze is shallow✓ Works in all modern browsers (ES5+)