Can u expain me this js code | most people don't know. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Can u expain me this js code | most people don't know.

var color = "#"+((1<<24)*Math.random()|0).toString(16); using this random color code is selected but still I didn't understand the code

2nd Feb 2018, 6:45 PM
Alex Advent
Alex Advent - avatar
3 Answers
+ 2
Hexadecimal is a base 16 number system where the maximum single digit is F (15). For comparison the decimal system is base 10 (maximum single digit is 9), and binary is base 2 (max single digit = 1). So, 0 and 1 are the same in all of them, but after that things change: 2 in decimal becomes 10 in binary. 15 in decimal becomes F in hex, and 1111 in binary. 255 in decimal becomes 1111-1111 in binary, and FF in hex. There is also an octal number system (base 8, maximum single digit = 7), but I haven't learned it yet. Colors have classically been defined as RGB (Red, Green, Blue) values in many programming languages, where each color is a value between 0 and 255. With transparency it's called ARGB where the A is an alpha or opacity value and also has a maximum value of 255. CSS helped simplify use of color values by allowing developers to define the colors with hex values using #000000-#FFFFFF, with the # telling the interpreter you're using a hex value instead of a color name, for example 'red'. CSS may not have been the first to do this, but it's where I learned it and IDK the history. In JS Math.random() generates a random number between 0 and 1, for example 0.19154. It will never be 1 though, so anything multiplied by the random value will be between 0 and value - 1. The value of 1 is 0000-0000-0000-0000-0000-0000-0000-0001 in binary because JS uses 32-bit values to store numbers. 1 << 24 is a binary operation which shifts the value 1 to the left 24 bits (single binary digits, a single 0 or 1) to create the magic value 0000-0001-0000-0000-0000-0000-0000-0000 in binary, or 0x1000000 in hex. Multiplying the magic number by this value creates a random value between 0x000000 and 0xFFFFFF because the JS interpreter also converts it back to a whole number in the process. Then by using toString(16) to convert the value to hex it's actually getting the hex value instead of a decimal (base 10) value. Very nice random generator for this specific purpose; beautifully simplistic.
2nd Feb 2018, 8:26 PM
Tom Shaver
Tom Shaver - avatar
+ 5
the .toString(16) limits the output to only hex (0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f) the (1<<24) makes the size of required hex digits, random randomizes it. the |0 makes sure that there is no decimal places after it. https://code.sololearn.com/W3Ko0L8hdhdC/?ref=app
2nd Feb 2018, 7:07 PM
Annabella Atherton Rosen
Annabella Atherton Rosen - avatar
+ 1
Thanks
4th Feb 2018, 9:53 AM
Alex Advent
Alex Advent - avatar