javascriptside-effectsjavascriptcore

In javascript, how "for .. in" statement can have side effect?


I want to know how for .. in can have any side effect?

let arr = [1.1, 2.2];
let obj = {x: 1, y: 1, z: 1};
for(let prop in obj) {
    ...
}

Considering above snippet code, is it possible to change some elements in arr at for .. in statement not in loop body?

I'm currently anaylzing JavaScriptCore JIT Compiler, DFG assumes that GetPropertyEnumerator has side-effect, which i understand that it can change some other object at for .. in statement.
But, i don't know how is this possible.
So i want to is this possible and if possible, how could i do that.


Solution

  • I found answer for this question myself :)
    https://github.com/WebKit/webkit/commit/243a17dd57da84426316502c5346766429f2456d
    Above commit log is very helpful for me !

    The Proxy object has member named getPrototypeOf.
    By using this getPrototypeOf, i can modify some objects during property lookup phase in for .. in statement.

    let a = {x: 1, y: 2, z: 3};
    a.__proto__ = {xx: 1, yy: 2, zz: 3};
    
    for(let i in a) {
        print(i);
    }
    

    Above one is simple example.
    The for .. in statement lookup the Object a's properties and then, follow a's __proto__ chain.
    In this context, Proxy's getPrototypeOf is trap for __proto__ lookup.
    Example is following one.

    let a = {
      x: 1,
      y: 2,
      z: 3
    };
    let p = new Proxy(a, {
      getPrototypeOf: function() {
        console.log("getPrototypeOf - side effects can be caused here");
        return {
          a: 1,
          b: 2
        };
      }
    });
    
    for (let i in p) {
      console.log(i);
    }