Code Logo

Getter Setter with defineProperty()

Published at25 Jul 2026
JavaScript Data Structures Hard 0 views
Like0

Write a JavaScript function that uses Object.defineProperty() to define a computed property on an object. The property 'double' should have a getter that returns the 'value' property multiplied by 2, and a setter that divides the input by 2 and stores it in 'value'.

Object.defineProperty() is a powerful JavaScript method for defining or modifying a property with fine-grained control. It can define data descriptors (value, writable) and accessor descriptors (get, set). Accessor descriptors use getter and setter functions that are called when the property is read or written, enabling computed properties and validation.

Unlike simple property assignment, defineProperty() allows configuring property attributes: configurable (can be deleted/redefined), enumerable (appears in for-in loops), and writable (can be changed). Accessor properties (get/set) cannot also have value or writable — these are mutually exclusive descriptor types.

Time complexity is O(1) for defineProperty and O(1) for each getter/setter invocation. Space complexity is O(1) per property. The getter and setter closures capture the object context which can be memory-relevant for large numbers of instances.

Edge cases include defining non-configurable properties (cannot be redefined or deleted), getters that throw errors, and ensuring the setter correctly transforms the value before storing.

Example Input & Output

Example 1
Input
{"value":5}
Output
10
Explanation

get double returns 5*2=10

Example 2
Input
{"value":0}
Output
0
Explanation

0*2=0

Example 3
Input
{"value":10}
Output
20
Explanation

10*2=20

Example 4
Input
{"value":7}
Output
14
Explanation

7*2=14

Example 5
Input
{"value":-3}
Output
-6
Explanation

-3*2=-6

Algorithm Flow

Recommendation Algorithm Flow for Getter Setter with defineProperty()
Recommendation Algorithm Flow for Getter Setter with defineProperty()

Solution Approach

function solution(obj) {
  Object.defineProperty(obj, 'double', {
    get: function() { return obj.value * 2; },
    set: function(val) { obj.value = val / 2; },
    enumerable: true,
    configurable: true
  });
  return obj;
}

Best Answers

javascript - Approach 1
function solution(obj) {
  Object.defineProperty(obj, 'double', {
    get: function() { return obj.value * 2; },
    set: function(val) { obj.value = val / 2; },
    enumerable: true,
    configurable: true
  });
  return obj;
}