JavaScript Object defineProperty() Method

The Object defineProperty() method is used to define a new property on an object or modify an existing one and returns the object.

Syntax

Object.defineProperty(obj, prop, descriptor)

Parameters

  1. obj: The object on which to define the property.
  2. prop: The name or Symbol of the property to be defined or modified.
  3. descriptor: The descriptor for the property being defined or modified. This can include: value, writable, configurable, enumerable, get and set.

Return value

Returns object that was passed to the function.

Visual Representation

Visual Representation of JavaScript Object defineProperty() Method

Example 1: How to Use Object.defineProperty() Method

let marvel = {}

Object.defineProperty(marvel, 'ironman', {
  value: 'Tony Stark'
})

console.log(marvel.ironman)

Output

Tony Stark

Example 2: Passing enumerable to true

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

let marvel = {}

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

console.log(marvel.ironman)

console.log(marvel)

Output

Tony Stark
{ ironman: 'Tony Stark' }

When you set enumerable to false, the property ironman will not be visible in the object’s enumeration.

let marvel = {}

Object.defineProperty(marvel, 'ironman', {
 value: 'Tony Stark',
 enumerable: false,
})

console.log(marvel.ironman)

console.log(marvel)

Output

Tony Stark
{}

Example 3: Modifying an existing property

let marvel = {}

Object.defineProperty(marvel, 'ironman', {
  value: 'Tony Stark',
  writable: false,
})

console.log(marvel.ironman)

marvel.ironman = 'RDJ' // No effect because writable is false
console.log(marvel.ironman)

Output

Tony Stark
{}

Example 4: Using Access Descriptors

let obj = {};

// Define a property with access descriptors
Object.defineProperty(obj, "serialNumber", {
 // Getter logs and returns the held value

 get: function() {
 console.log("Retrieving the Value...");
 return valueHolder;
 },

 // Setter logs and stores the new value
 set: function(newValue) {
 console.log("Assigning a New Value...");
 valueHolder = newValue;
 },
 enumerable: true,
 configurable: true
});

// Set and then get the serialNumber property
obj.serialNumber = 17;
console.log("Serial Number:", obj.serialNumber);

Output

Assigning a New Value...
Retrieving the Value...
Serial Number: 17

Leave a Comment

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