0

Can some one please explain to me in a layman's what is happening in the loop as it iterates to produce the statement (the objects properties are in an array).

var o = {x:1, y:2, z:3};
var a = [], i = 0;

for (a[i++] in o)
{
    console.log(o);
}
1
  • 5
    Something very basic for you Java != Javascript. Commented Oct 17, 2013 at 12:35

2 Answers 2

2

This is how the for/in loop is evaluated:

for each property in object o
     assign the property name to the left hand side, that is a[i++]

Initially i = 0, so:

  1. a[0] will get x. // notice it gets the property name, not its value
  2. a[1] will get y.
  3. a[2] will get z.

NOTE: i++ is equal to i = i + 1.

The previous code is equivalent to the following:

var o = {x:1, y:2, z:3};
var a = []
var i = 0;

for (propertyName in o)
{
    a[i] = propertyName;
    i = i + 1;
    console.log(o);
}
Sign up to request clarification or add additional context in comments.

Comments

0

It assigns an object with three keys (x,y,z) to o. It assigns an empty array to a, and the number 0 to i.

The for ( in ) loop will iterate over an object's properties, but first the condition is evaluated.

i++ is evaluated first. The ++ is a post-increment operator and is notorious for people getting the damn thing wrong. Douglass Crockford (search for him) suggests not using it. It returns the value stored in i (which was 0) then increments it.

So now i is storing 1, and we're evaluating a[0], which is accessing an element in an array, except... that array is empty (we're accessing an undefined value).

It now looks at in o, which iterates through the keys in o, which there are 3 of. Thus, it iterates the loop three times. Each time it then logs the object to the console.

Whatever this code is, I'd suggest replacing it. It shouldn't be something you want to see in code. It's confusing and surely doesn't do anything meaningful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.