Reputation: 791
When I read YDKJS book in there say:
There's a nuanced exception to be aware of: even if the property is already configurable:false, writable can always be changed from true to false without error, but not back to true if already false.
"use strict";
const obj = Object.create(null);
Object.defineProperty(obj, "name", {
value: "Murad",
writable: true,
configurable: false,
enumerable: true
});
Object.defineProperty(obj, "name", {
value: "Tofiq",
writable: false,
configurable: false,
enumerable: true
});
But this is so interesting for me why JS have exception for writable?
Upvotes: 1
Views: 2058
Reputation: 11034
It's not a bug, it's by design
It is deliberately designed in the Language and implemented in v8
From MDN Docs
When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its configurable attribute set to false the property is said to be “non-configurable”. It is not possible to change any attribute of a non-configurable accessor property. For data properties, it is possible to modify the value if the property is writable, and it is possible to change writable attribute from true to false. It is not possible to switch between data and accessor property types when the property is non-configurable.
A TypeError is thrown when attempts are made to change non-configurable property attributes (except value and writable, if permitted) unless the current and new values are the same.
When the writable property attribute is set to false, the property is said to be “non-writable”. It cannot be reassigned.
But the error is thrown only in strict
mode to enforce immutable types
Upvotes: 2