Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Proxy set property trap not firing for array length

When working with JavaScript ES6 Proxies, the set property trap for array.length does not fire when assigning array indexes directly.

For example:

const proxy = new Proxy([], {
    set: function(obj, name, value) {
        console.log(`set: ${name}`);
        obj[name] = value;
        return true;
    }
});
proxy.push(0);
proxy[1] = 1;

Chrome 51 and Firefox 47 outputs:

set: 0  
set: length  
set: 1

While I would expect:

set: 0  
set: length  
set: 1  
set: length 

Is this per spec? I couldn't find any information on this.

like image 442
kgreen Avatar asked Jun 23 '16 10:06

kgreen


1 Answers

There is no need to explicitly set the length property when a value is assigned to an index. The reason why it's set with push is indeed defined in the specification:

  1. Repeat, while items is not empty

    a. Remove the first element from items and let E be the value of the element.

    b. Let setStatus be Set(O, ToString(len), E, true).

    c. ReturnIfAbrupt(setStatus).

    d. Let len be len+1.

  2. Let setStatus be Set(O, "length", len, true).

Basically: If an error happens then set the correct length in case the array already has been expanded.

like image 96
a better oliver Avatar answered Oct 26 '22 11:10

a better oliver