JavaScript(JS) object method - defineProperties

www‮.‬theitroad.com

The Object.defineProperties() method in JavaScript is used to define multiple new properties for an object or modify existing ones. This method is a way to define properties that have special characteristics such as getters and setters, or are read-only, or not enumerable.

The syntax for using Object.defineProperties() method is as follows:

Object.defineProperties(obj, props)

Here, obj is the object for which we want to define properties, and props is an object that contains the properties we want to define.

The props object has property names as its keys and property descriptors as its values. Each property descriptor is an object that describes the property we want to define. The possible keys for the property descriptor object are:

  • value: The value of the property.
  • get: A function that gets the value of the property.
  • set: A function that sets the value of the property.
  • writable: A Boolean value indicating whether the property can be modified.
  • enumerable: A Boolean value indicating whether the property will be enumerable when iterating over the object's properties.
  • configurable: A Boolean value indicating whether the property can be deleted or its attributes can be changed.

For example, let's say we have an object person with a name property:

const person = {
  name: 'John'
};

We can use the Object.defineProperties() method to define a new property age for the person object with writable and enumerable attributes:

Object.defineProperties(person, {
  age: {
    value: 30,
    writable: true,
    enumerable: true
  }
});

console.log(person.age); // Output: 30

In this example, we defined a new property age for the person object using the Object.defineProperties() method. The age property has a value of 30, and its writable attribute is set to true, which means that its value can be changed. Its enumerable attribute is also set to true, which means that it will be enumerable when iterating over the object's properties.

We can also define multiple properties at once using the Object.defineProperties() method. For example, we can define both age and gender properties for the person object:

Object.defineProperties(person, {
  age: {
    value: 30,
    writable: true,
    enumerable: true
  },
  gender: {
    value: 'Male',
    writable: false,
    enumerable: true
  }
});

console.log(person.age); // Output: 30
console.log(person.gender); // Output: 'Male'

In this example, we defined both age and gender properties for the person object using the Object.defineProperties() method. The age property has a value of 30 and its writable and enumerable attributes are set to true. The gender property has a value of 'Male', but its writable attribute is set to false, which means that its value cannot be changed.