When Assignments Don’t Work in JavaScript
In JavaScript is possible that simple assignment statement will occassionally fail. This is not due to a bug, but has to do with a language feature here is an example of what this could look like:
obj.property1 = []; obj.property2 = []; obj.property1.push(1); obj.property2.push(1); // Uncaught TypeError: Cannot read property 'push' of undefined
If you look at this closely, it is saying that obj.property2 has no push property since it is undefined and not an array. Despite the previous lines code assigning it. Although this looks like a bug, it is actually because the assignment operation of obj.property2 was overridden and no assignment function was given in the place of the default one. Here is the earlier code
const obj = { property1: [{ id: 'object-1' }], }; Object.defineProperties(obj, { property2: { get: getProperty2 }, }); function getProperty2() { return undefined; };
In this case, the error would be pretty obvious. But sometimes the code to generate the object is very separated from the code to use or update an object. Some environments like Node.js will show a more obvious error around the assignment like TypeError: Cannot set property property2 of #<object> which has only a getter, but many still do not. So this is something to keep in mind. I personally prefer to avoid overwriting fundamental operations like assignment when possible to avoid confusiong errors like this.
Github Location: https://github.com/Jacob-Friesen/obscurejs/blob/master/2017/getterIssue.js












