Search code examples
javascriptecmascript-6es6-proxy

ES6 Proxy logs an unexplainable extra value


So far I have understood ES6 proxies as a way to add intercepts to allow you to add custom behavior to your code. Implemented this code snippet to intercept a push into an array but it logs an extra the extra 'trapped! 1' after a push and I cannot figure out why. Does anyone know why it does this? And does this mean the code in the trap is run twice?

const handler = {
  set(target, propertyKey, value, receiver) {
    console.log('trapped!', value);
    return Reflect.set(target, propertyKey, value, receiver);
  }
};

const p = new Proxy([], handler);
p.push('a')


Solution

  • It's setting the length as well as the index of the array you're pushing onto. That's why it runs twice for every push.

    let handler = {
      set(target, propertyKey, value, receiver) {
        console.log(`set ${propertyKey} to ${value}`)
        return Reflect.set(target, propertyKey, value, receiver);
      }
    };
    
    const p = new Proxy([], handler);
    p.push('a')