How to use JavaScript Object.defineProperty?

If you want to define a new or modify a property on an object, then use the Object.defineProperty in JavaScript. Use the property like the following −

Object.defineProperty(obj, prop, descriptor)

The following are the parameters −

  • obj – Property is defined on this object. 
  • prop – Name of the property 
  • descriptor  − The descriptor for the property


You can try to run the following code to learn how to implement Object.defineProperty in JavaScript −

<!DOCTYPE html>
         const obj = {};

         Object.defineProperty(obj, 'prop', {
            value: 20,
            writable: false
         obj.prop = 10;