Skip to content

JavaScript Object defineProperty() | Method

  • by

JavaScript Object defineProperty() Method is used to define a new property directly on an object or modify an existing property on an object.

The method takes three parameters: the object to define the property on, the name of the property, and an object that describes the property.

Object.defineProperty(obj, prop, descriptor)

This method allows you to define various attributes for a property, such as its value, writable status, and whether it can be deleted or not. By using defineProperty(), you can add custom logic to the getter and setter methods of a property, allowing you to control how it is accessed and updated.

const obj = {};
Object.defineProperty(obj, 'readOnlyProp', {
  value: 'This property is read-only',
  writable: false
});

console.log(obj.readOnlyProp); // This property is read-only
obj.readOnlyProp = 'Trying to modify read-only prop'; // no error thrown but will not change
console.log(obj.readOnlyProp); // This property is read-only

This method is commonly used for creating read-only properties or for implementing computed properties that are dynamically generated based on other properties.

JavaScript Object defineProperty() example

Simple example code.

<!DOCTYPE html>
<html>
<body>
    <script>
      // create an object named user
        let user = {};
    
    Object.defineProperty(user, "name", {
        value: "John",
        writable: false
        });

    // attempt to change the name property
    user.name = "NO One";
    console.log(user)

    </script>
</body>
</html>

Output:

JavaScript Object defineProperty() Method

First create an empty object named user. Then use Object.defineProperty() to define a new property name on the user object. The value attribute is set to "John", and the writable attribute is set to false. This means that the name property is read-only and cannot be modified once it is set.

Do comment if you have any doubts or suggestions on this Js object methods topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading