Object Property descriptor option writable in Javascript
An object property descriptor option writable used to configure whether specified property should allows to change the value. If value for the option set to false, it will be read only property and does not allows to change. The default value will be true for all JavaScript object.
Syntax
 1 Object.defineProperty(<object>, <property>, <descriptor>);
object : An object to define new or modify an existing property
property : A new or an existing property to define in the specified object
descriptor : A descriptor for the property being defined or modified
Descriptor object Syntax
 1 {
 2   value: <value>,
 3   writable: boolean,
 4   enumerable: boolean,
 5   configurable: boolean
 6 }
Descriptor writable option
 1 const emp = { id: 1, name: 'JavaScript' };
 2 
 3 Object.defineProperty(emp, 'salary', {
 4   value: 1000,
 5   writable: true, // enable by setting true
 6   enumerable: false,
 7   configurable: false
 8 });
 9 
 10 emp.salary = 2000; // it allows to change value
 11 console.log(emp.salary); // prints 2000
In the above example, an emp object define with properties and values. A new property is added using defineProperty() method by specifying option writable to true. A new value for the property salary is set to 2000 which update new value and printed on console.
Note : If writable option value set to false, it want allows to modify existing value for the specified property. It is also possible to update the default descriptor options as shown below.
Disable existing property using writable option
 1 const emp = { id: 1, name: 'JavaScript', salary: 1000 };
 2 
 3 // other descriptor options are optional
 4 Object.defineProperty(emp, 'salary', {
 5   value: 1000,
 6   writable: false, // disable by setting false
 7   enumerable: false,
 8   configurable: false
 9 });
 10 
 11 emp.salary = 2000; // does not allows change value
 12 console.log(emp.salary); // prints 1000
In the above example, an emp object define with properties and values. An existing property salary descriptor value is changed using defineProperty() method by specifying writable option to false. A new value for the property salary is set to 2000 which does not update the new value and printed old value on console.
Privacy Policy
Terms of Service
Disclaimer
Contact us
About us