Open In App

JavaScript Object defineProperties() Method

Last Updated : 26 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Object.defineProperties() method in JavaScript is a standard built-in Object that defines a new or modifies existing properties directly on an object and it returns the object.

Syntax: 

Object.defineProperties(obj, props) 

Parameter: 

  • Obj: This parameter holds the object on which the properties are going to be defined or modified.
  • Props: This parameter is an object whose own enumerable properties constitute descriptors for the properties to be defined or modified.

Return Value: This method returns an object which is passed as an argument to the function.

Below examples illustrate the Object.defineProperties() method in JavaScript:

Example 1: In this example, we will define new properties to an object using the Object.defineProperties() method in JavaScript.

javascript




const geek = {};
  
Object.defineProperties(geek, {
    prop1: {
        value: "geeksforgeeks",
        writable: true
    },
    prop2: {}
});
  
console.log(geek.prop1);
console.log(geek.prop2);


Output: 

"geeksforgeeks"
undefined

Example 2: In this example, we will define new properties and modify some properties of an object using the Object.defineProperties() method in JavaScript.

javascript




let geek = {};
Object.defineProperties(geek, {
    'prop1': {
        value: "Geeks",
        writable: true
    },
    'prop2': {
        value: 'Hello',
        writable: false
    }
});
console.log(geek.prop2);
console.log(geek.prop1);
  
const geek1 = {};
Object.defineProperties(geek1, {
    prop1: {
        value: "Hi",
        value: "Hello",
        value: "Namaste",
    },
    prop2: {
        value: " And ",
    },
    prop3: {
        value: "learn",
        value: "Stay Safe",
    }
});
  
console.log(geek1.prop1, geek1.prop2, geek1.prop3);


Output: 

"Hello"
"Geeks"
"Namaste" " And " "Stay Safe"

We have a complete list of Javascript Object methods, to check those please go through this JavaScript Object Complete Reference article.

Supported Browsers: The browsers supported by Object.defineProperties() method are listed below: 

  • Google Chrome 6.0 and above
  • Internet Explorer 9.0 and above
  • Mozilla 4.0 and above
  • Opera 11.1 and above
  • Safari 5.0 and above


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads