Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

figuring out an array loop

    this.spaces = [];

    var x, y;
    for (x=1; x <= width; x += 1) {
        this.spaces[x] = [];
        for (y=1; y <= height; y += 1) {
            this.spaces[x][y] = "(" + x + "," + y + ")";                  
        }

    }

}

I'm trying to decode a javascript workshop in treehouse. I'm not quite getting how the [x]in the second for loop can start at 1. I'm restricted to the idea of index starting at zero. anyone have an idea of what's happening here.

1 Answer

in a nested for loop the outer loop's starting value is maintained until the inner loop completes, so since x=1, x is 1 for the first trip through the inner loop. when that finishes, x increments and the inner loop runs again.

Where I'm stumped is I'm thinking that the second for loop is building into the array. this.spaces[0][1] is how I would think it should be but in reality its this.spaces[1][1] is how its starting and I'm having trouble with that.