Object.defineProperty
Learn how to enforce immutability through `Object.defineProperty`. Learn how it ties into functional programming.
Object.defineProperty
This function allows us to create properties on an object, but specify some rules that the engine will enforce. For example, we can make it so that the property can’t be changed, deleted, or printed in a loop.
Usage
Object.defineProperty
takes in three arguments:
- The object on which we want to define a property
- The name of the property we want to define
- An object containing both the value we’d like to give our property and the rules we would like to enforce on our property
value
There are four optional items we can place in our rules object. One of them is value
and simply allows us to give our property a value.
writable
, configurable
, enumerable
The remaining three are booleans which, by default, are set to false
. They remove some piece of functionality from our object.
When discussing them, we’ll first manually set them to true
. As we discuss each one, we’ll make it false
in the examples. Initially setting them all to true
will help us understand them one by one.
value
To provide the value for the property we’re adding to our object, we place a value
property on our options object. It defaults to undefined
if it’s not provided.
Get hands-on with 1200+ tech skills courses.