How to enforce immutability to prevent the modification of values in JavaScript

2 Answers

0 votes
// Immutable User Object in JavaScript (Enforce Immutability)

/*
    JavaScript does NOT enforce immutability by default,
    but you can achieve it using:

    1. const variable binding        -> prevents reassignment of the variable
    2. Object.freeze()               -> prevents adding/changing/removing properties
    3. Deep freeze function          -> prevents mutation of nested objects
    4. No setters                    -> prevents intentional mutation

    Below is a complete program showing all of these.
*/

// Deep freeze function to make nested objects immutable
function deepFreeze(obj) {
    Object.freeze(obj); // freeze top-level

    // Recursively freeze nested objects
    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);

// The following lines would fail silently in non‑strict mode,
// or throw errors in strict mode:

// User.id = 100;          // Cannot modify frozen object
// User.name = "Tim";      // Cannot modify frozen object
// User.age = 30;          // Cannot add new properties
// delete User.name;       // Cannot delete properties




/*
run:

ID: 42
Name: Jade

*/

 



answered 8 hours ago by avibootz
0 votes
// 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>

*/

 



answered 7 hours ago by avibootz
edited 7 hours ago by avibootz
...