What is Object.defineProperty() in Javascript?

Object.defineProperty() is a method that allows you to define your own properties on an object. It takes three arguments: the object to modify, the name of the property, and a function to define the property's value.

Here's an example:

let myObj = {};
Object.defineProperty(myObj, "length", {
    value: function() {
    return this.length;

This code defines a new property, length, on myObj. The value of the property is a function that returns the length of the object. You can also use Object.defineProperty() to change the value of an existing property:

Object.defineProperty(myObj, "length", {
	value: 10

Now the length property on myObj has a value of 10. Object.defineProperty() can also be used to delete properties:

Object.defineProperty(myObj, "length", {
	delete: true

Now the length property will be deleted from myObj if it is ever set.

Want to sponsor matcha.fyi? You can have your brand featured right here. Let's connect and chat about it.