RGB variable syntax with "+R+", "+G+", "+B+"

Hi,
In 5.10 step 10-14 or so…Pardon my ignorance, but what is the rationale behind surrounding the R, G and B variables in + and " marks? I just need to be able to explain this to the students and I, frankly, don’t know the answer. Help!
Lee

1 Like

Nevermind!!

var color = “rgb(”+R+","+G+","+B+")"; in the code is read as rgb( concatenated with the value of R concatenated with , concatenated with the value of G concatenated with , concatenated with the value of B concatenated with )

I didn’t start reading from the left to right and just looked at the “” on the outside of the whole expression first.

This makes perfect sense. Sorry to have bothered anyone with this. One of my sharper students politely clarified this for me.

2 Likes

Im a little confused just as you were. So does “++” mean concatenation in the javascript language?

In JavaScript ++ is used to increment a value by 1 ( x = x + 1 ). When concatenating Strings, you just need one plus sign: var total = "The total is " + x ;.

In this case we are combining random rgb values, using individual variables.
To establish the random values, we first assign the variables to a range of numbers.
var r = randomNumbers(0,255);
var g = randomNumbers(0,255);
var b = randomNumbers(0,255);

We then apply them to the rgb statement using concatenation and a short cut:
var color = rgb"( "+r+", "+g+", "+b+")";

This is the full version of the code:
var color = "rgb("+randomNumber(0,230)+","+randomNumber(0,230)+","+randomNumber(0,230)+")";

Since we declared and initialized variables for each rgb value, we use the simpler short cut. It reads as stated above:
rgb( concatenated with the value of r concatenated with , concatenated with the value of g concatenated with , concatenated with the value of b concatenated with rgb);

1 Like