Getter Setter with defineProperty()
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
get double returns 5*2=10
0*2=0
10*2=20
7*2=14
-3*2=-6
Algorithm Flow

Solution Approach
Best Answers
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;
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
