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

Alexander D
Alexander D
4,448 Points

Why am I getting 11 dots?

Hello there,

I saw great codes for this challenge. A little disappointed as I was forced to see into the solution. Still, I am getting 11 dots rather than 10, why is that?

My code is the following (I know it can be made way drier):

var i;
var html = '';
var red;
var green;
var blue;
var rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';

function getRandomColors () {

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);

}

for (i = 0; i <= 10; i++) {

 getRandomColors();
}

Thanks for your support!

1 Answer

Robin Siegl
Robin Siegl
11,037 Points

This for loop runs until the variable i is not less or equal than 10.
i = 0 -> Loop runs
i = 1 -> Loop runs
i = 2 -> Loop runs
i = 3 -> Loop runs
i = 4 -> Loop runs
i = 5 -> Loop runs
i = 6 -> Loop runs
i = 7 -> Loop runs
i = 8 -> Loop runs
i = 9 -> Loop runs
i = 10 -> Loop runs

i = 11 -> Loop doesn't run anymore

To solve this you need to remove the equal sign:

for (i = 0; i < 10; i++) {
 getRandomColors();
}
Alexander D
Alexander D
4,448 Points

Thanks, I lost myself in a glass of water!

I do appreciate your response! :)