These lessons are picked from next.js open source code. In this article, you will learn how to create an unwritable property using Object.defineProperty.
Object.defineProperty
Object.defineProperty() is used to add a new property directly to an object.
If you are looking to practice next.js, checkout my website: https://tthroo.com/
Execute the following in your browser’s console.
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: false,
});
Try to make the following modification using the same console:
object1.property1 = 11
Because writable is set to false, you are not able to modify the property1 value. MDN docs has awesome documentation about this.
Object.defineProperty has data descriptor like shown in the above image and accessor descriptor (this is what is used in next.js source code explained below)
Where is Object.defineProperty used in nextjs codebase?
You can find Object.defineProperty used in next.js code here.
Conclusion:
You do not have the flexibility to make a property unwritable when you create an object using const obj = {}. In case, if you ever need to have an unwritable property in an object, use Object.defineProperty with unwritable set to false.
Get free courses inspired by the best practices used in open source.
About me:
Website: https://ramunarasinga.com/
Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/
Github: https://github.com/Ramu-Narasinga
Email: ramu.narasinga@gmail.com
Top comments (0)