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

ddeveloper
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
ddeveloper
Full Stack JavaScript Techdegree Graduate 15,281 Points

Why is 'i' not in the actual code? 'i' is in the for loop initialization, but 'i' is not in the actual code.

Why is 'i' not in the actual code? 'i' is in the for loop initialization, but 'i' is not in the actual code execution between the '{ }'

It works for me but I would like clarification because I was expecting to put 'i' in the code itself.

Steven Parker
Steven Parker
229,732 Points

Please show the code that you have this question about.

2 Answers

ddeveloper
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
ddeveloper
Full Stack JavaScript Techdegree Graduate 15,281 Points
var html = '';
var red;
var green;
var blue;
var rgbColor;

for ( var i = 1; i <= 100; i += 1) {
  red = Math.floor(Math.random() * 256 );
  green = Math.floor(Math.random() * 256 );
  blue = Math.floor(Math.random() * 256 );
  rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
  html += '<div style="background-color:' + rgbColor + '"></div>';  
}

document.write(html); 
Steven Parker
Steven Parker
229,732 Points

The value of "i" is only used to control how many times the loop runs, it is not needed inside the loop block. You could,, however, modify the code if you wanted to place the value inside each created "div":

  html += '<div style="background-color:' + rgbColor + '">' + i + "</div>";
ddeveloper
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
ddeveloper
Full Stack JavaScript Techdegree Graduate 15,281 Points

thanks for the quick reply.

ok I see why var htm = ' ' ; was declared at line 1.

thanks for clarifying. My understanding of the 'i' is becoming more clear.

Whatever code is inside of the { } of the for loop will run the number of times specified in the for loop (in this case when is is equal to or less than 100 it will keep running. Once it's greater than 100 it will stop).

it will generate a red, green, blue, then concatenate them into the value of the rgbColor variable; finally it will add the value of the rgbColor variable inside of a div element. It will repeat these steps 100 times thus creating 100 divs.

Steven Parker
Steven Parker
229,732 Points

That's right, the loop variable controls the number of repeats whether or not it is used in the loop body.