Why and how does this work?

Note: migrating question from outside freecodecamp, because I’m having a hard time understanding it.

when I run:

var html = '';
var red;
var green;
var blue;`
var rgbColor;

for(var i = 0; i < 4; i++) {
  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);
}

I get 10 divs with 10 random colors.

But when I change it to:

var html = '';
var red;
var green;
var blue;
var rgbColor;

for(var i = 0; i < 4; i++) {
  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);

It generates only 4, the expected.

Can somebody explain why? Thank you.

Hi, sorry, not an answer: I’ve just cleaned your code up. You don’t need the backticks at the start and end of each line, you only need the three at the start and end of the whole block. I’ve removed those single backticks on each line: just makes things easier to read and it means the code can be copied and pasted somewhere to check it.

1 Like

Thanks DanCouper I was unsure on how to undo extra backticks.

1 Like

You should be able to edit the post: if you click the … at the bottom one of the options should be a little pencil icon: I’m not sure what all the constraints on it are though (there’s a window of time when you’re allowed to edit), bit you should be able to modify your post.

1 Like

It’s pretty straightforward.

Think about the value of html at the end of each loop in the first example, versus it’s value in the second example.

Clue, in the first example you write the value of html four times…

1 Like

Doesn’t everytime I write it, one div with one color is then created? This is confusing me badly. Ive been staring at it for about 2 hours.

The first iteration sets html to be one div with a colour and writes that to the screen.

The second iteration adds another div to the existing html variable and then prints both…

So loop 1 prints something like:
a ab abc abcd

Whereas loop 2 prints:
abcd

So loop 2 only prints html once, when it has all 4 divs in it. Loop 1 prints four times while html grows between each step.

1 Like