Question

`I'm reading 'JavaScript: the definitive guide' and I'm getting hung up on an example:

“you can use code like the following to copy the names of all object properties into an array"

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

"following the code above with this line enumerates the array indexes 0, 1, and 2"

for(i in a) console.log(i);

Can someone please explain to me like I'm five how the first for/in loop works? It seems to me a[i++] would evaluate to 1 on the first time through the loop, not 0.

Was it helpful?

Solution

Can someone please explain to me like I'm five how the first for/in loop works?

A for-in loop does allow any left-hand-side expression (that is, something you could possibly assign to) before the in, not only plain variables. So

for(a[i++] in {x:1, y:2, z:3})

is just the same as

a[i++] = "x";
a[i++] = "y";
a[i++] = "z";

It seems to me a[i++] would evaluate to 1 on the first time through the loop, not 0.

i++ is a postfix expression, so no - it will yield the value 0 (that i had before) and then increment it. See ++someVariable Vs. someVariable++ in Javascript for details.

OTHER TIPS

You're confused by the time at which your variable i is incremented. You could expect i to evaluate to 1 only if you do for(a[++i] in o) /* empty */;

It's called post/pre increment. Post will increment after your instruction, and pre will increment before.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top