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

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,
});

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.

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.