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 hsl color code.
function randomColor() {}
The function returns a random hsl color string.
Each color component (hue, saturation, lightness) is generated using Math.random()
and then rounded down to the nearest whole number using Math.floor()
hue value is generated between 0 and 360.
saturation value is generated between 0 and 100.
lightness value is generated between 0 and 100.
Generate a random hue value between 0-360
const h = Math.floor(Math.random() * 360) h
Generate a random saturation value between 0-100
const s = Math.floor(Math.random() * 101) s
Generate a random lightness value between 0-100
const l = Math.floor(Math.random() * 101) l
Return the hsl color string.
return `hsl(${h}, ${s}%, ${l}%)`
Generate random color.
function randomColor() {
const h = Math.floor(Math.random() * 360);
const s = Math.floor(Math.random() * 101);
const l = Math.floor(Math.random() * 101);
return `hsl(${h}, ${s}%, ${l}%)`;
}
call function
randomColor(); → hsl(352, 44%, 47%)
randomColor(); → hsl(41, 59%, 44%)
randomColor(); → hsl(168, 17%, 54%)
Function returns a random color after each call.
hsla → hsl with optional alpha value
hsla color values are an extension of hsl color values with an alpha channel - which specifies the opacity for a color.
hsla(hue, saturation, lightness, alpha)
alpha represents the alpha channel value of the output color.
0 corresponds to 0% fully transparent
1 corresponds to 100% fully opaque