JavaScript Object.defineProperties() Example

The Object.defineProperties() method defines new or modifies existing properties directly on an object, returning the object.

Example 1 - Adding multiple properties

var user = {
    firstName : 'Ramesh',
    lastName : 'Fadatare',
    emailId : 'ramesh@gmail.com',
    age : 29
};

Object.defineProperties(user, {
    fullName: {
      value: user.firstName + " " + user.lastName,
      writable: true
    },
    phoneNo: {
        value: 123456789
    },
    dob : {

    },
  });
  
console.log(user);
Output:
{firstName: "Ramesh", lastName: "Fadatare", emailId: "ramesh@gmail.com", age: 29, fullName: "Ramesh Fadatare", …}
age: 29
emailId: "ramesh@gmail.com"
firstName: "Ramesh"
lastName: "Fadatare"
dob: undefined
fullName: "Ramesh Fadatare"
phoneNo: 123456789
For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.
You can refer below screenshot for your testing:

Example 2

var obj = {};
Object.defineProperties(obj, {
  'property1': {
    value: true,
    writable: true
  },
  'property2': {
    value: 'Hello',
    writable: false
  }
  // etc. etc.
});

Comments