Science Knowings: JavaScript Course For Social Media

Object.getOwnPropertyDescriptors() Method

Previously Discussed Topic: Object.fromEntries() Method

We previously explored the utility of Object.fromEntries() method, which allows you to create objects from key-value pair arrays.

Object.getOwnPropertyDescriptors() Method

The Object.getOwnPropertyDescriptors() method is a built-in JavaScript method that provides a detailed description of all properties of an object, including their attributes and configuration (

Object.getOwnPropertyDescriptors(object)
).

What is Object.getOwnPropertyDescriptors() Method?

The Object.getOwnPropertyDescriptors() method returns an object with properties that describe the own properties of an object, including the value, enumerability, configurability, and writability of each property.

Syntax

Object.getOwnPropertyDescriptors(obj)

Parameters

  • obj: The target object whose properties are to be described.
  • Return Value

  • An object with properties that describe the own properties of the object, including the value, enumerability, configurability, and writability of each property.
  • Example: Getting All Property Descriptors

    const obj = { name: 'John', age: 30 };
    const descriptors = Object.getOwnPropertyDescriptors(obj);
    console.log(descriptors); // Object { name: {...}, age: {...} }

    Example: Getting Specific Property Descriptors

    const descriptor = Object.getOwnPropertyDescriptor(obj, 'age');
    console.log(descriptor); // { value: 30, writable: true, enumerable: true, configurable: true }

    Use Cases

  • Inspecting an object's properties and attributes
  • Modifying an object's properties
  • Creating a new object with the same properties as another object
  • Detecting if a property exists in an object
  • Examples

  • Check if a property is writable:
    const obj = { name: 'Alice' };
    if (Object.getOwnPropertyDescriptor(obj, 'name').writable) {
      obj.name = 'Bob'
    } 
  • Freeze an object's properties:
    const obj = { name: 'John' };
    Object.freeze(obj);
    const descriptor = Object.getOwnPropertyDescriptor(obj, 'name');
    descriptor.configurable = false;
  • Create a new object with the same properties:
    const obj1 = { name: 'John', age: 30 };
    const obj2 = Object.create({}, Object.getOwnPropertyDescriptors(obj1));
  • Edge Cases

  • Object.getOwnPropertyDescriptors() only returns the object's own properties. It does not include inherited properties.
  • Polyfills

    Not required for modern browsers.

    Next Topic: Object.getOwnPropertyNames() Method

    In the next session, we will dive into the Object.getOwnPropertyNames() method, which provides an array of all the property names (both enumerable and non-enumerable) of an object. Don't miss out!