Skip to content Skip to sidebar Skip to footer

How Do I Make A Specific Property Of An Object Immutable In Javascript?

if I have an object like let person = { firstName: 'Krishna', lastName: 'Jai', age: 12 } person.firstName = 'Kumar'; console.log(person); //output Object { f

Solution 1:

If you already have a property in place, you can modify it's descriptor's writable property to false like that:

Object.defineProperty(person, 'firstName', {
      writable: false,
      configurable: false
});

configurable: false should be specified to prevent future modifications of the firstName property, e.g. changing writable back to true.

Read more here about property descriptors.

If you're defining a property that didn't exist before, then all descriptor properties are defaulted to false and the only things you need to specify are value and enumerable:

Object.defineProperty(person, "firstName", {
    value: "Krishna",
    enumerable: true
});

Solution 2:

You have a couple of options, but probably the simplest is to make a read-only, non-configurable property:

let person = {
    lastName: 'Jai',
    age: 12
};
Object.defineProperty(person, "firstName", {
    value: "Krishna",
    enumerable: true
});

The flags writable and configurable both default to false when, as above, you're defining a new property. (You don't have to make it enumerable, as far as that goes, but...)

Example:

let person = {
    lastName: 'Jai',
    age: 12
};
Object.defineProperty(person, "firstName", {
    value: "Krishna",
    enumerable: true
});
console.log("before: ", person.firstName);
person.firstName = "Mohinder";
console.log("after setting in loose mode:", person.firstName);
functionfoo() {
    "use strict";
    console.log("trying to set in strict mode:");
    person.firstName = "Mohinder"; // Error
}
foo();

Or if you want to apply the change after the fact, you need to specify the flags:

let person = {
    firstName: "Krishna",
    lastName: 'Jai',
    age: 12
};
Object.defineProperty(person, "firstName", {
    writable: false,
    configurable: false
});

Example:

let person = {
    firstName: "Krishna",
    lastName: 'Jai',
    age: 12
};
Object.defineProperty(person, "firstName", {
    writable: false,
    configurable: false
});
console.log("before: ", person.firstName);
person.firstName = "Mohinder";
console.log("after setting in loose mode:", person.firstName);
functionfoo() {
    "use strict";
    console.log("trying to set in strict mode:");
    person.firstName = "Mohinder"; // Error
}
foo();

Solution 3:

You could use a getter method and omit the setter.

let person = {
       getfirstName() { return'Krishna'; },
       lastName: 'Jai',
       age: 12
    };

person.firstName = 'Kumar';
console.log(person);

Post a Comment for "How Do I Make A Specific Property Of An Object Immutable In Javascript?"