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 trialMarina Mas
6,104 PointsWhy do we need to declare the variable i ?
Why is the variable i inside the for loop declared? Why is it running in the javascript console without declaration?
1 Answer
Jonathan Grieve
Treehouse Moderator 91,253 PointsIt's what's known as a counter variable
. What's happening is the loop needs a way to track how many times it should run the loop.
It's typical to have a look that has a letter for a name such as i.
for(let i=0; i< iterable_name.length; i++) {
}
So in this example, you initialise a variable with let i = 0
or another value other than 0 to start the count.
In the next part, you specify a condition for how the loop will end. It could be a hard coded value but it's more common to have the loop run for however many times as there are values in an iterable such as an array. hence iterable_name.length
;
The third and final part is the incremental value which governs how many steps the loop runs until it gets to the break of the loop. i++ is a short hand for changing the value upwards by one.