How to Create a new Property using Data Descriptors in JavaScript

How to Create a new Property using Data Descriptors in JavaScript

In this article, I am going to discuss How to Create a new Property using Data Descriptors in JavaScript with Examples. Please read our previous article where we discussed JavaScript Object Property Descriptors with Examples.

How to Create a new property using Data Descriptors in JavaScript

When the property does not exist in an object, the Object.defineProperty() method creates the new property with a given value and property flags on an object using Property descriptor (data and accessor descriptor) otherwise if the property exists in an object, this method updates its flags. If a flag is not specified, it is considered false by default.

We will evaluate this with an example, for that we have created an empty object person using object literal and added a property firstName to an object named person using Object.defineProperty() method using data descriptors, then to get property descriptor full information about property firstName of person object for that we are using Object.getOwnPropertyDescriptor() method (as we already discuss getOwnPropertyDescriptor() in Object.getOwnPropertyDescriptor() method chapter)and passing object name person with property name firstName as parameters.

Later we are printing it using JSON.stringify() method as is used to print the JavaScript object returned by Object.getOwnPropertyDescriptor function. What we discussed above is given in the below example.

Example1: JavaScript Objects, add new property and get info using Object.getOwnPropertyDescriptor() descriptor
<html>
<head>
    <title> JavaScript Objects, add new property and get info using Object.getOwnPropertyDescriptor() descriptor example1</title>
</head>
<body>
    <script>
        //Creates a Person Object
        let person = {
            firstName: "Angel",
            lastName: "Kathy",
            age: 25,
            location: "India"
        };

        //to get object full information including property descriptor and flags
        let descriptor = Object.getOwnPropertyDescriptor(person, 'firstName');

        //JSON.stringify is used to print the JavaScript object returned by Object.getOwnPropertyDescriptor function.
        console.log(JSON.stringify(descriptor, null, 2))

    </script>
</body>
</html>
Output:

How to Create a new Property using Data Descriptors in JavaScript with Examples

We saw from the above example for property firstName of object person all the property flags are false by default. we can change them anytime. Now let’s see the effects of the property flags discussed earlier, by example.

In the below example we have used two-sample codes. In the first sample code we have created a Person object with few properties and then used the Object.defineProperty() method to add a new property Pincode on the existing Person object. As Object.defineProperty() defines a new property when the property does not exist in the object.

In the second sample code, we have created an empty object obj after that we are defining a new property firstProp on obj object. Here we saw how we can define a property on an empty object as well as on an existing object. What we discussed above is given in the below example.

Example2: JavaScript Objects, add new property using Object.defineProperty() method
<html>
<head>
    <title>JavaScript Objects, add new property using Object.defineProperty() method example2</title>
</head>
<body>
    <script>
        //sample code1
        //Creates a Person Object
        let person = {
            firstName: "Angel",
            lastName: "Kathy",
            age: 25,
            location: "India"
        };

        //method defineProperty() to add property to an object or modifies attributes of an existing property
        Object.defineProperty(person, 'pincode', {
            value: 400100,
            writable: false
        });

        //display data
        console.log("*****Sample Code1*****");
        console.log("person object: ", person)
        console.log("person object length: ", Object.getOwnPropertyNames(person).length) //returns no. of keys present in an object
        console.log("person object properties names using Object.getOwnPropertyNames: ", Object.getOwnPropertyNames(person)) //return ALL property keys.
        console.log("person Object literal type? : ", typeof person);// object

        //sample code2
        // Creates a new empty object
        var obj = {};

        //object property added with
        //defineProperty with a data property descriptor
        Object.defineProperty(obj, 'firstProp', {
            value: 10,
            writable: true
        }); // 'firstProp' property added in the Obj object and its value is 10

        //display data
        console.log("*****Sample Code2*****");
        console.log("obj object: ", obj)
        console.log("obj object length: ", Object.getOwnPropertyNames(obj).length) //returns no. of keys present in an object
        console.log("obj object properties names using Object.getOwnPropertyNames: ", Object.getOwnPropertyNames(obj)) //return ALL property keys.
        console.log("obj Object literal type? : ", typeof obj);// object

    </script>
</body>
</html>
Output:

How to Create a new Property using Data Descriptors in JavaScript

Example3: JavaScript Objects, add or update new property using Object.defineProperty() method
<html>
<head>
    <title>JavaScript Objects, add or update new property using Object.defineProperty() method example3</title>
</head>
<body>
    <script>
        //sample code1
        //Creates a student Object
        let student1 = {};

        //method defineProperty() to add property to an object or modifies attributes of an existing property
        Object.defineProperty(student1, 'marks1', {
            value: 65,
            writable: false
        });
        student1.marks1 = 50;

        //display data
        console.log("*****Sample Code1*****");
        console.log("student1 object: ", student1)
        console.log("student1 object length: ", Object.getOwnPropertyNames(student1).length) //returns no. of keys present in an object
        console.log("student1 object properties names using Object.getOwnPropertyNames: ", Object.getOwnPropertyNames(student1)) //return ALL property keys.
        console.log("student1 Object literal type? : ", typeof student1);// object
        console.log("student1 marks1 : ", student1.marks1);// 65

        //sample code2
        // Creates a new empty object
        var student2 = {};

        //object property added with
        //defineProperty with a data property descriptor
        Object.defineProperty(student2, 'marks2', {
            value: 20,
            value: 30,
            value: 12 * 8,
            writable: false
        }); // 'marks2' property added in the Obj object and its value will be over-write by the last one that is 96

        //display data
        console.log("*****Sample Code2*****");
        console.log("student2 object: ", student2)
        console.log("student2 object length: ", Object.getOwnPropertyNames(student2).length) //returns no. of keys present in an object
        console.log("student2 object properties names using Object.getOwnPropertyNames: ", Object.getOwnPropertyNames(student2)) //return ALL property keys.
        console.log("student2 Object literal type? : ", typeof student2);// object
        console.log("student2 marks2 : ", student2.marks2);// 96

    </script>
</body>
</html>
Output:

How to Create a new Property using Data Descriptors

In the next article, I am going to discuss How to Modify a property using Data Descriptors in JavaScript with Examples. Here, in this article, I try to explain How to Create a new Property using Data Descriptors in JavaScript with Examples and I hope you enjoy this How to Create a new Property using Data Descriptors in JavaScript with Examples article.

Leave a Reply

Your email address will not be published.