AppDividend
Latest Code Tutorials

Javascript Object defineProperty Example | Object.defineProperty() Tutorial

0

Javascript Object defineProperty Example | Object.defineProperty() Tutorial is today’s topic. The static method Object.defineProperty() defines the new property directly on the object, or modifies an existing property on the object, and returns an object.Object.defineProperty() allows the precise addition to or modification of the property on the object. Normal property addition through assignment creates the properties which show up during a property enumeration (for…in loop or Object.keys() method), whose values may be changed and may be deleted.

Javascript Object defineProperty Example

When a property specified doesn’t exist in an object, Object.defineProperty() creates the new property as described. Fields may be omitted from a descriptor, and default values for those fields are inputted.

Syntax

The syntax of Object.defineProperty is following.

Object.defineProperty(obj, prop, descriptor)

obj: The object on which to define the property.

prop: The name or Symbol of the property to be defined or modified.

descriptor: The descriptor for the property being defined or modified.

See the following example.

// app.js

const marvel = {}
Object.defineProperty(marvel, 'ironman', {
  value: 'Tony Stark'
})
console.log(marvel.ironman)

The output is following.

 

Javascript Object defineProperty Example

So, we have defined the property on marvel object.

Now, let’s print the object.

// app.js

const marvel = {}
Object.defineProperty(marvel, 'ironman', {
  value: 'Tony Stark'
})
console.log(marvel)

The output is following.

 

Object.defineProperty() Tutorial

See, the object is empty, but when you try to print the property, it gives its value.

We can use enumerable property. The enumerable is true if and only if this property shows up during enumeration of the properties on the corresponding object.

Now, add an enumerable property to true while defining a property on an object.

// app.js

const marvel = {}
Object.defineProperty(marvel, 'ironman', {
  value: 'Tony Stark',
  enumerable: true,
})
console.log(marvel.ironman)
console.log(marvel)

Okay, let’s see the output.

 

Javascript Object defineProperty Example Tutorial

Modifying a property

Now, let’s change the existing property.

// app.js

const marvel = {}
Object.defineProperty(marvel, 'ironman', {
  value: 'Tony Stark',
  enumerable: true,
  writable: true,
  configurable: true
})
console.log(marvel.ironman)
marvel.ironman = 'RDJ'
console.log(marvel.ironman)
console.log(marvel)

The output is following.

 

Javascript Object defineProperty Example | Object.defineProperty() Tutorial

Finally, Javascript Object defineProperty Example | Object.defineProperty() Tutorial is over.

 

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.