JS: Watch out Object.defineProperty()

TLDR; Check x2 how your Getter & Setter work! You might not get what you’re expecting.

The problem:

  1. Define a property of an object with a Getter that returns an array.
  2. Setter should not allow to set smaller arrays & should concat the same array to itself. (Example: [1,2] -> [1,2,1,2])
Code sample on JS Bin
jsbin.com

Or the code here, … I’m sorry for Medium’s formatter. :(

var tmp = {};
function getPropertyDescription() {
 var innerArray = [];
 
 return {
 get: function () {
 return innerArray;
 },
 
 set: function (_newValue) {
 console.log( ‘SET’, _newValue);
 if (_newValue.length < innerArray.length) return;
 innerArray = _newValue.concat(_newValue);
 } 
 } 
}
Object.defineProperty( tmp, ‘arr’, getPropertyDescription());
//
console.log( ‘Initial: ‘, tmp.arr);
tmp.arr.push( 1); // MODIFIED CONTENT !!! 
console.log( ‘After push: ‘, tmp.arr); // EXPECT [1,1]
tmp.arr = [1,2,3]; // [1,2,3,1,2,3]
tmp.arr = [1]; // won’t assign
console.log( ‘After assign: ‘, tmp.arr); // [1,2,3,1,2,3]
tmp.arr.splice(0, 1); // MODIFIES CONTENT !!!
console.log( ‘After splice: ‘, tmp.arr); // EXPECT [2,3,2,3]

Will show us:

Initial: []
After push: []
SET [1, 2, 3]
After assign: [1, 2, 3]
After splice: [2, 3]

Is it an expected result?

What do you think?

Show your support

Clapping shows how much you appreciated Pavel B.’s story.