// Immutable User Object in JavaScript
"use strict";
/*
In strict mode, modifying a frozen object throws TypeError.
We use:
- const → prevents reassignment
- Object.freeze() → prevents mutation
- deepFreeze() → prevents nested mutation
*/
// Deep freeze function to freeze nested objects
function deepFreeze(obj) {
Object.freeze(obj);
for (const key of Object.keys(obj)) {
const value = obj[key];
if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
deepFreeze(value);
}
}
return obj;
}
// Create an immutable User object
const User = deepFreeze({
id: 42,
name: "Jade"
});
console.log("ID:", User.id);
console.log("Name:", User.name);
// Attempt 1: modify id
try {
User.id = 100; // Cannot assign to read only property 'id'
} catch (e) {
console.log("Exception:", e.message);
}
// Attempt 2: modify name
try {
User.name = "Bob"; // Cannot assign to read only property 'name'
} catch (e) {
console.log("Exception:", e.message);
}
// Attempt 3: add new property
try {
User.age = 30; // Cannot add property age
} catch (e) {
console.log("Exception:", e.message);
}
// Attempt 4: delete property
try {
delete User.name; // Cannot delete property 'name'
} catch (e) {
console.log("Exception:", e.message);
}
/*
run:
ID: 42
Name: Jade
Exception: Cannot assign to read only property 'id' of object '#<Object>'
Exception: Cannot assign to read only property 'name' of object '#<Object>'
Exception: Cannot add property age, object is not extensible
Exception: Cannot delete property 'name' of #<Object>
*/