JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops The Refactor Challenge Solution

Shane Harley
Shane Harley
2,843 Points

When 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 Parker
Steven Parker
182,307 Points

The 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.

Steven Vallarsa
Steven Vallarsa
Full Stack JavaScript Techdegree Student 8,372 Points

It 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
Shane Harley
2,843 Points

That makes sense! So generally just stick to i = 0 unless I find some other weird reason to use something different

Thanks!