Reputation: 1
I have encountered an interesting behavior in JavaScript that I am struggling to understand. When I try to redefine the 'length' property of an array using Object.defineProperty, I get different exceptions based on whether I use a literal string or a concatenated string as the property name. Here are the two code snippets:
Object.defineProperty([], 'length', {value: -1, configurable: true});
Object.defineProperty([], 'len' + 'gth', {value: -1, configurable: true});
The first code snippet throws a RangeError: Invalid array length, while the second one throws a TypeError: Cannot redefine property: length.
I understand that the 'length' property of an array is special in JavaScript and cannot be set to a negative value. What I don't understand is why the type of exception differs based on whether I use a literal string or a concatenated string as the property name.
Is this behavior defined by the ECMAScript specification, or is it dependent on the JavaScript engine implementation? Can anyone provide some insights into this?
The first code snippet throws a RangeError: Invalid array length, while the second one throws a TypeError: Cannot redefine property: length.
why ?
Upvotes: 0
Views: 33