Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

DefineProperty in JavaScript

DefineProperty is one of the ways in which you can add a new property to a JavaScript Object. You can also use it to Modify the property. We usually use it, when we want to alter the property descriptors or flags.

DefineProperty

The method defineProperty() adds a new property directly on an object, or modifies an existing property on an object, and returns the object.

Syntax

        
 Object.defineProperty(obj, prop, descriptor)
 
 
                
        
    

Where

obj is the object on which, we want to add a new property or modify an existing property.

prop is the name of the Property (or Symbol of the property) that we want to add or modify.

descriptor for the property being added or modified.

If the property prop doesn’t exist in the object, Object.defineProperty() creates a new property. If it already exists its descriptor is modified.

The defineProperty property method returns the updated obj after adding or modifying its property.

Descriptor

The Property Descriptors hold the configurations of an object’s property.

There are two kinds of Properties in JavaScript. They are Data Property & Accessor Property

The Data Propertyis normal key-value pair. The Accessor property uses the Getter & Setters Methods. Property Descriptors are different for the Data Properties & Accessor Properties.

The Property Descriptors for the Data Property are known as the data descriptor and that of the accessor property is known as the accessor descriptor.

Both the Descriptors are objects. Both of them contain configurable & enumerable properties. The data descriptor also has value & writable properties, while the accessor descriptor has get & set properties.

When creating a new property using the defineProperty, if the fields are omitted from the descriptor, the defineProperty will use the false as default values for configurable , enumerable & writable property.

DefineProperty Examples

Adding a Property

In the following example, we create an empty person object.

Later we add the firstName property to the person object with the value of Bill.

        
const person = {};
 
//Adding the firstName to the person object with the value 'Bill'
Object.defineProperty(person, 'firstName', {
  value: "Bill",
  writable: true,
  configurable:true,
  enumerable:true
});
 
console.log(person);    //{firstName: "Bill"}
 
 
                
        
    

The above code is the same as the following code

        
const person = {};
person.firstName="Bill"
console.log(person);    //{firstName: "Bill"}
 
 
                                
                            

Adding a getter & setters Property

The following example. shows how to add a getter & setter property

        
product ={
  name : "Computer",
  price : 35000,
  _discount:0, // private member
}
 
 
 
Object.defineProperty(product, "discount", {
    get: function () {
      return this._discount;
    },
    set: function (value) {
      console.log('setting discount '+value)  
      this._discount = value;
      if (this._discount > 80) _discount = 80;
    },
    configurable: true,
    enumerable: true,
  });
 
 
console.log(product.discount)
 
product.discount=100
console.log(product.discount)
 
 
                                
                            

Adding Multiple Properties

The following example adds multiple properties to a person object ( name accessor property & age data property).

        
const person = {};
 
 Object.defineProperty(person, "_name", {
   value: "",
   writable: true,
   configurable: true,
   enumerable: true,
 });
  
 Object.defineProperty(person, "name", {
   get() {
     return this._name;
   },
   set(value) {
     this._name = value;
   },
   configurable: true,
   enumerable: true,
 });
  
 Object.defineProperty(person, "age", {
   value: "30",
   writable: true,
   configurable: true,
   enumerable: true,
 });
  
 
 
                                
                            

DefineProperties

To add multiple properties, we can make use of the DefineProperties method. It is similar to DefineProperty but allows us to add or modify multiple properties

Syntax

        
Object.defineProperties(obj, props)
 
                
        
    

Where

obj is the object on which, we want to add or modify properties

props is an object whose each property must be a descriptor (either a data descriptor or an accessor descriptor). The name of the key becomes the property name.

The following example shows, how you can add multiple properties using the DefineProperties method.

        
const person = {};
 
 obj= {
   _name : { value: "",    writable: true,  configurable: true,   enumerable: true,  },
   name  : {   get() {
     return this._name;
   },
   set(value) {
     this._name = value;
   },  configurable: true,   enumerable: true,  },
   age   : { value: "30",  writable: true,  configurable: true,   enumerable: true,  }
 }
  
  
 Object.defineProperties(person,obj);
  
 console.log(person)
 
                
        
    

Modifying an existing property

If the property already exists, then Object.defineProperty() modify the property.

In the following example, we use defineProperty to modify the firstName.

        
const person = {};
person.firstName="Bill"
console.log(person);    //{firstName: "Bill"}
 
 
Object.defineProperty(person, 'firstName', {
  value: "Gates",
  writable: true,
  configurable:true,
  enumerable:true
});
 
 
console.log(person)  //{firstName: "Gates"}