-3

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?

connexo
  • 53,704
  • 14
  • 91
  • 128
  • 2
    Why do you think “the loop never iterates”? – deceze Sep 05 '21 at 06:52
  • 1
    Isn't the output `["x","y","z"]`? – Gaël J Sep 05 '21 at 06:55
  • Does this answer your question? [How do I loop through or enumerate a JavaScript object?](https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – Gaël J Sep 05 '21 at 06:56
  • 3
    Your loop iterates three times (number of own keys of `o`). Both your expectation and your claimed observation are wrong. Output is `["x","y","z"]`. – connexo Sep 05 '21 at 07:01

2 Answers2

2

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);.

Gaël J
  • 11,274
  • 4
  • 17
  • 32
0

The for...in statement iterates over all enumerable properties of an object that are keyed by strings.

for (variable in object) {
  statement
}

variable A different property name is assigned to the variable on each iteration.

object Object whose non-Symbol enumerable properties are iterated over.