Let's say you have an object called John
.
const John = {};
Now we can add the name
property and assign it a value of John Doe
and also make it a not changing or immutable property.
We can acheive this through the Object.defineProperty()
static method.
const John = {};
// setting property name: "John Doe"
// and also making it immutable
Object.defineProperty(John, "name", {
value: "John Doe",
writable: false,
});
The method accepts:
- The object to add the property as the first parameter, in our case
John
. - The name of the property you want to add to the object as the second parameter, in our case the
name
property. - The third parameter is called descriptor where we are setting the
value
option to the value we want in ourname
property in our case "John Doe" andwritable
property tofalse
for making it immutable.
Now if you try to change the value of the name
in object John
, It will throw an error in strict mode.
// will throw an error
John.name = "Lily";