Javascript Object.defineProperties()

The JavaScript Object.defineProperties() method adds or modifies properties on an object and returns object.

The syntax of the defineProperties() method is:

Object.defineProperties(obj, props)

The defineProperties() method, being a static method, is called using the Object class name.


defineProperties() Parameters

The defineProperties() method takes in:

  1. obj - The object on which to define or modify properties.
  2. props - An object whose keys represent the names of properties to be defined or modified and whose values are objects describing those properties.
    Each props value must either be a data descriptor or accessor descriptor. They can have the following optional properties.
    1. configurable
    2. enumerable
    Data descriptors can also have:
    1. value
    2. writable
    Accessor descriptors can also have:
    1. get
    2. set

Return value from defineProperties()

  • Returns the object that was passed to the function.

Note: If a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. If a descriptor has both value or writable and get or set keys, an exception is thrown.


Example: Using Object.defineProperties()

let obj = {};
Object.defineProperties(obj, {
  property1: {
    value: true,
    writable: true,
  },
  property2: {
    value: "Hello",
    writable: false,
  },
});

console.log(obj); // {property1: true, property2: "Hello"}

Output

{property1: true, property2: "Hello"}

Recommended Reading: Javascript Object defineProperty()