JavaScript Object DefineProperties Method

JavaScript Object DefineProperties Method with Examples

In this article, I am going to discuss JavaScript Object DefineProperties Method with Examples. Please read our previous article where we discussed JavaScript Object getOwnPropertyDescriptors with Examples

JavaScript Object.defineProperties() Method

We already have seen Object.defineProperty() method in Property Flag chapter, we will be going to learn about Object.defineProperties() method which is same as like Object.defineProperty() method with little difference.

The Object.defineProperties() method is a JavaScript standard built-in object method used for adding multiple new properties or updating the existing multiple properties of an object, it returns an object that was passed as an argument to the method, or we can say that it returns a modified object.

In other words, the Object.defineProperties() method allows to define a new or modify existing multiple properties of an object at once, it returns the modified object.

Syntax to use Object.defineProperties() Method in JavaScript

Syntax to use Object.defineProperties() Method in JavaScript

Parameters:
  1. Obj: The object name on which multiple new properties need to be added or modified.
  2. Properties: It represents the names of the properties which have to be added or modified. Each value in properties must be either a data descriptor or an accessor descriptor; it cannot be both for more (see Object.defineProperty() for more details).
Return Value:

It returns an object that was passed as an argument to the method.

Note: In Addition, JavaScript provides us with a list of property descriptors that help us to shape how the property behaves. The Property Descriptor with some of the following attributes:

Property Descriptors in JavaScript

Property descriptors present in Object.defineProperty() come in two main varieties:

  1. Data Descriptors:
  2. Accessor Descriptors (Property Accessor):

Both data descriptors and accessor descriptors are objects. They share the below listed optional keys.

Note that: the defaults value mentioned here are in the case when properties are defined using Object.defineProperty() without any parameters:

  1. configurable: By default, it is false. When set to true that means the type of this property descriptor can be modified or updated later and the property can be deleted from the respective object.
  2. enumerable: By default, it is false. When set to true that means this property can be counted and show up when iterating using a loop (for… in) are called enumerable or during enumeration of the properties. To check whether a property is enumerable or not, the function called propertyIsEnumerable() is used. It returns true if the object property is enumerable otherwise returns false.
Data Descriptors in JavaScript:

A data descriptor is a value of a property, which can or cannot be writable(modify).

  1. Required fields: value or writable or both also
  2. Optional fields: configurable, enumerable

 Example:

// An object property added with defineProperty with a data property descriptor
 Object.defineProperty(objPerson, "age", {
     value: 10,
     writable: true,
     enumerable: false, 
     configurable: false
 });

A data descriptor also has the following attributes:

  1. value: By default, it is undefined. It is the value of the property defined. The value can be any JavaScript value that is a number, string, function, object, etc.
  2. writable: By default, it is false. it is read-only. When set to true that means the value of the property can be changed by using the assignment operator (=) followed by the new value of a property.
Accessor Descriptors (Property Accessor) in JavaScript:

A data descriptor is a value of a property, which can or cannot be writable(modify). An accessor descriptor or property accessor is a property described by a getter-setter accessor combination of functions. A descriptor must be one of these two options: either getter or setter, it cannot be both.

Getter is for reading or fetching the property value whereas setter is for setting a new or modifying the existing value of a property.

  1. Required fields: get or set or both
  2. Optional fields: configurable, enumerable
Example:
//An object property added with defineProperty with an accessor property   descriptor
 var oldValue =30;
 Object.defineProperty(objPerson, "carSpeed", {
     get: function () {
         return oldValue;
     },
     set: function (newValue) {
         oldValue = newValue;
     },
     enumerable: true,
     configurable: true
 });

An accessor descriptor/property accessor also has the following optional:

  1. get: By default, it is undefined. It’s a get method that is a getter for the property, it makes the property read-only. This method returns a value of the property which means it is used for getting/fetching the property value. If no getter is provided it is undefined.
  2. set: By default, it is undefined. It’s a set method that is a setter for the property, it makes the property writable. This method accepts a new value as an argument getting assigned to the property which means it is used for setting a new value or modifying the existing value of a property. If no setter is provided it is undefined.

If a property descriptor does not have value, writable, get, and set keys, it is considered a data descriptor. An exception is thrown If a property descriptor has both [value or writable] and [get or set] keys.

Note that: By default, the property added by using the Object.defineProperties() method are immutable (Objects whose value cannot be changed) and not enumerable (an object that cannot be counted and doesn’t show up when iterating using loop are called non-enumerable). In short, the property added by this method is not enumerable, not configurable, and not writable as defaults.

//Not enumerable, not configurable, not writable as defaults. When no flags are provided
Object.defineProperties(obj, properties)

When creating a property using Object.defineProperties() if there is no attribute specified in the object. This method will use their default values. That means Properties created using the method Object.defineProperties() have an enumerable flag set to false by default, a configurable flag set to false by default, and a writable flag set to 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 few multiple new properties firstName and lastName to an object named person using Object.defineProperties() method using data descriptors, then to get property descriptor full information about all the properties such as firstName and lastName of person object for that we are using Object.getOwnPropertyDescriptors() method (as we already discuss getOwnPropertyDescriptors() in Object.getOwnPropertyDescriptors() method chapter)and passing object name person as parameters.

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

Example: JavaScript Objects, add multiple new properties and get all property info using Object.getOwnPropertyDescriptors() property descriptor
<html>
<head>
    <title> JavaScript Objects, add multiple new properties and get all property info using Object.getOwnPropertyDescriptors() property descriptor example1</title>
</head>
<body>
    <script>
        //Creates a Person Object
        let person = {};

        //method defineProperties() to add new multiple properties to an object or modifies attributes of an existing property
        Object.defineProperties(person, {
            'firstName': {
                value: 'Angel',
                writable: false
            },
            'lastName': {
                value: 'Kathy',
                writable: false
            }
        });

        //to get object full information including all property descriptor and flags
        let descriptor = Object.getOwnPropertyDescriptors(person);

        //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:

JavaScript Objects, add multiple new properties and get all property info using Object.getOwnPropertyDescriptors() property descriptor

We saw from the above example for all properties of an object person all the property flags are false by default. We can change them anytime.

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.defineProperties() method to add multiple new property’s locations and Pincode on the existing Person object. As Object.defineProperties() defines multiple new properties 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 multiple new properties firstProp and secondProp on the 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.

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

        //method defineProperties() to add new multiple properties to an object or modifies attributes of an existing property
        Object.defineProperties(person, {
            'location': {
                value: 'India',
                writable: false
            },
            '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
        //method defineProperties() to add new multiple properties to an object or modifies attributes of an existing property
        Object.defineProperties(obj, {
            'firstProp': {
                value: 10,
                writable: true
            },
            'secondProp': {
                value: 100,
                writable: true
            }
        });

        //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:

blank

Example: JavaScript Objects, add new and update multiple properties using Object.defineProperties() method
<html>
<head>
    <title>JavaScript Objects, add new and update multiple properties using Object.defineProperties() method example3</title>
</head>
<body>
    <script>
        //sample code1
        //Creates a student Object
        let student1 = {};

        //method defineProperties to add multiple properties to an object or modifies attributes of an existing property
        Object.defineProperties(student1, {
            'name': {
                value: 'Maria',
                writable: true
            },
            'greeting': {
                value: 'Hello',
                writable: false
            },
            'marks1': {
                value: 65,
                writable: false
            },
            'marks2': {} //empty property
        });

        student1.marks1 = 50; //update marks1 property

        //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 name property: ", student1.name); //name property
        console.log("student1 greeting property: ", student1.greeting);
        console.log("student1 marks1 property: ", student1.marks1); // 65, cannot update as writable is false
        console.log("student1 marks2 empty property: ", student1.marks2);  //undefined as property is empty

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

        //object property added with
        //method defineProperties to add multiple properties to an object or modifies attributes of an existing property
        Object.defineProperties(student2, {
            'marks1': {
                value: 20,
                value: 30,
                value: 12 * 8,
                writable: false
            },// 'marks1' property added in the student2 object and its value will be over-written by the last one that is 96
            'greeting': {
                value: 'Hi',
                value: 'Hello',
                value: 'Welcome'
            },
            'message1': {
                value: "and"
            },
            'message2': {
                value: "always",
                value: "keep learning"
            }
        });

        //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 greeting property: ", student2.greeting);
        console.log("student2 marks1 property: ", student2.marks1); // 96
        console.log("student2 message1 property: ", student2.message1);
        console.log("student2 message2 property: ", student2.message2);

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

JavaScript Objects, add new and update multiple properties using Object.defineProperties() method

Example: JavaScript Objects, update existing multiple properties using Object.defineProperties() method
<html>
<head>
    <title>JavaScript Objects, update existing multiple properties using Object.defineProperties() method example4</title>
</head>
<body>
    <script>
        //sample code1
        //Creates a student Object
        let student1 = {
            'name': 'Maria',
            'greeting': 'Hello',
            'marks1': 65,
            'marks2': 70
        };

        //method defineProperties to update existing multiple properties to an object or modifies attributes of an existing property
        Object.defineProperties(student1, {
            'greeting': {
                value: 'Welcome',
                writable: false
            },
            'marks1': {
                value: 90,
                writable: false
            },
            'marks2': {
                value: 75
            }
        });

        //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 name property: ", student1.name); //name property
        console.log("student1 greeting property: ", student1.greeting);
        console.log("student1 marks1 property: ", student1.marks1); // 90
        console.log("student1 marks2 property: ", student1.marks2); //75

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

JavaScript Objects, update existing multiple properties using Object.defineProperties() method

Here, in this article, I try to explain JavaScript Object DefineProperties Method with Examples and I hope you enjoy this JavaScript Object DefineProperties Method with Examples article.

Leave a Reply

Your email address will not be published.