Why empty array is getting initialized during the “for in ” loop of javascript without assignment? [closed]



var a=[],i=0,o={x:1,y:2,z:3}
for(a[i++] in o);
console.log(a);

output in Mozilla developer console : Array [ "x", "y" ]

I expect array to be empty as the loop never iterates. But it is initialized with ‘x’ and ‘y’ .

What could be the reasonable explanation?

Answer

the loop never iterates

Yes, it does.

for(key in o); means for each key as key of the object o

Thus the loop iterates 3 times with 3 values "x", "y" and "z".

Then comes the trick that you can assign these values into the array by using the syntax for(a[i++] in o);.



Source: stackoverflow