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 Object-Oriented JavaScript: Part 1

Initializing Maze.spaces array - index of element

Hi!

I see video (around 17:20) and i see for iteration starting from index 1.

Why? JS indexes for array are starting from 0!

3 Answers

Hi Denis,

I too like using 0-based arrays, and I agree with you that losing track of the 0 cell might cause a problem for bug hunters. So I wish that he had accounted for that in his program with a comment, such as /* cells [1..n] used in this array, [0] left undefined */

Take care sir

-- Cal

Hi Denis,

I see what he's doing.. He is declaring an array, but he is not using the cell of 0 index.

His loops indicate indexes running i=1 to 1 <= height (or width). The cells with index 0 do exist, but they are just undefined. He's just not using those spots.

Try this with his code: alert(y.length); It should print whatever the height is, plus 1. So the 0 index cell does exist. Then try this: alert(y[0]); This should print "undefined", not used in his program. Similar with array x.

If he used the index 0 spot, his code would always have to say something like "the first position index, which is 0 not 1; the last position index, which is the size minus 1" and so on. He's wasting two cells in his program, but saving millions of cells in his own brain!

Take care!

-- Cal

Yup. I do understand that JS array indexes are zero-based, same for many-many other languages. This is why i did not understand why in program was used 1-based indexes. IMHO, only old languages are using 1 based indexes.

Here is more info: https://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28array%29#Array%5Fsystem%5Fcross-reference%5Flist

Maybe using 1 based array index can same some brain cells for now, but i m sure that this practice will lead to millions brain cells lost for bug hunting in future programs! IMHO, its better to use proper indexes instead "more simple".

I just come across with this and realized why he is doing this after reading the comments. But does this have any advantage that way? :)