+ 1

JS Random rbg colors

function r() { return Math.floor(Math.random() * 255) } var color = 'rgb(' + r() + "," + r() + "," + r() + ')'; This was one of the explanations from reddit showing how to generate random colors via rgb. Like why doesn't this work??? var color = 'rgb(Math.floor(Math.random()*255), Math.floor(Math.random()*255), Math.floor(Math.random()*255))' I thought you can input numbers from 0-255 into rgb and the bit of code below: Math.floor(Math.random()*255) will output a number. Can someone explain the need to surround every entry of rgb with + and "" ???

2nd May 2019, 5:41 PM
J3fro C
J3fro C - avatar
3 Réponses
+ 3
J3fro C Template Literals(es6) may be the thing you need. A template literal is a way to concatenate strings while allowing embedded expressions and improving readability. color = `rgb(${r()},${g()},${b()})` ref-source: https://codeburst.io/javascript-what-are-template-literals-5d08a50ef2e3
3rd May 2019, 12:08 AM
ODLNT
ODLNT - avatar
+ 1
If you use only one set of quotes around the whole operation, you do no operation at all - you just create a big string. A string doesn't mind if there's 'Hello World' in it or something that looks like code. So what you need to do is make the calculations separately and then turn the result into string format, which will automatically happen if you combine numbers and strings with +.
2nd May 2019, 5:46 PM
HonFu
HonFu - avatar
0
Messing around with rgb and hsl more. I noticed that rgb and hsl ONLY accepts numbers as inputs. So no variables that have an integer value or a function. Relating to my initial query above, why can't we use variables and functions as an input for these rgb and hsl? I feel like I just have to accept that I have to concatenate all of it like as though it's a mix of strings and variables. Just don't get how Javascript can recognise that the string is an actual function.
2nd May 2019, 7:26 PM
J3fro C
J3fro C - avatar