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 trialShane Harley
2,960 PointsWhen to use var i = 0 vs var i = 1?
Hi! Curious why sometimes either of these are used. Is there a reason I'd start with var i = 1?
3 Answers
Steven Vallarsa
10,842 PointsIt comes down to usage. Iterables like Arrays, Lists and the like start at index zero, because… reasons! (Way back in the Pleistocene age of computing the brainiacs decided that the first index should be zero instead of one, and so we're stuck with it to this day.) But it does make sense in when you think about it. Starting a "for loop" at zero also allows you to get the length of the collection and just use a "<" symbol instead of having to also type an equal sign "<=". Sorry, not much of a justification, but that's all I can think of at the moment :)
You can start the for loop at any digit you want, so long as you keep track of where it's going to end. But once you start iterating through arrays, you'll want to start them at zero.
Shane Harley
2,960 PointsThat makes sense! So generally just stick to i = 0 unless I find some other weird reason to use something different
Thanks!
Steven Parker
231,275 PointsThe reason is probably based on what the variable is being used for. When a loop is used with an array, the index is set to 0 to begin since that's the value to index the first array element. To be able to offer an explanation for other cases or values, we'd need to see more of the code where it is used.
When in doubt about the pertinent code for a question, always show the entire program. If using workspaces, you can make a snapshot of your workspace and post the link to it here.