DEV Community

Cover image for Lessons from opensource: Use Object.defineProperty to create an unwritable object’s property.
Ramu Narasinga
Ramu Narasinga

Posted on • Edited on

Lessons from opensource: Use Object.defineProperty to create an unwritable object’s property.

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,
});
Enter fullscreen mode Exit fullscreen mode

Try to make the following modification using the same console:

object1.property1 = 11
Enter fullscreen mode Exit fullscreen mode

Object.defineProperty()

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.

https://github.com/vercel/next.js/blob/canary/packages/next/src/client/router.ts#L89

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

Learn the best practices used in open source.

Top comments (0)