Numbers are used to represent both integer and floating-point values.
Numbers are most commonly expressed in literal forms like 255 or 3.14159 ↴
let num1 = 5; → number
let num2 = 2.5; → number
let num3 = num1 + num2;
console.log(num3); returns ↴
7.5 → number
Generate random colors using ↴
Math.random() static method → returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1.
Math.floor() static method → always rounds down and returns the largest integer less than or equal to a given number.
Random number generation process of generating a number that is not predictable.
Math.random() static method returns a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive), with approximately uniform distribution over that range, which can be scaled to a desired range.
Math.random() always returns a number lower than 1
Math.random(); → 0.7409774889800926
Math.random(); → 0.5533596609238658
Math.random(); → 0.26768267226253617
Returns random numbers between 0 (inclusive) and 1 (exclusive)
Math.floor() static method always rounds down and returns the largest integer less than or equal to a given number.
Math.floor(5.25); → 5
Math.floor(2.99); → 2
Math.floor(6.55); → 6
Rounds down and returns the largest integer less than or equal to a given number.
Define a function randomColor to generate a random color in rgb color code.
function randomColor() {}
The function returns a random rgb color string.
Each color component (red, green, blue) is generated using Math.random()
multiplied by 256 to cover the full range of RGB values,
and then rounded down to the nearest whole number using Math.floor()
Generate a random integer between 0-255 for the red component.
const r = Math.floor(Math.random() * 256) r
Generate a random integer between 0-255 for the green component.
const g = Math.floor(Math.random() * 256) g
Generate a random integer between 0-255 for the blue component.
const b = Math.floor(Math.random() * 256) b
Return the RGB color string.
return `rgb(${r}, ${g}, ${b})`
Generate random color.
function randomColor() {
const r = Math.floor(Math.random() * 256);
const g = Math.floor(Math.random() * 256);
const b = Math.floor(Math.random() * 256);
return `rgb(${r}, ${g}, ${b})`;
}
call function
randomColor(); → rgb(171, 67, 81)
randomColor(); → rgb(180, 138, 46)
randomColor(); → rgb(118, 158, 150)
Function returns a random color after each call.
rgba → rgb with optional alpha value
rgba color values are an extension of rgb color values with an alpha channel - which specifies the opacity for a color.
rgba(red, green, blue, alpha)
alpha represents the alpha channel value of the output color.
0 corresponds to 0% fully transparent
1 corresponds to 100% fully opaque
rgb values are each resolved to a number between 0-255 inclusive.
alpha channel value is resolved to a number between 0-1 inclusive.