If you're starting with JavaScript and want to understand how to work with random numbers, round them down, and store values in arrays โ you're in the right place!
๐ข 1. Math.random()
: Generating Random Numbers
Math.random()
is a built-in JavaScript function that returns a random decimal number between 0
(inclusive) and 1
(exclusive).
console.log(Math.random()); // e.g., 0.7238475932
But most of the time, we want random whole numbers โ not decimals. Thatโs where Math.floor()
comes in.
๐งฎ 2. Math.floor()
: Rounding Down Numbers
Math.floor()
takes a number and rounds it down to the nearest whole number.
console.log(Math.floor(4.9)); // Output: 4
console.log(Math.floor(7.1)); // Output: 7
You can use both Math.random()
and Math.floor()
together to get a random integer.
// Random number between 0 and 9
let randomNumber = Math.floor(Math.random() * 10);
console.log(randomNumber);
Hereโs how it works:
-
Math.random()
โ gives a number like 0.7382 -
* 10
โ scales it to 7.382 -
Math.floor()
โ turns it into 7
๐ฆ 3. Arrays: Storing Multiple Values
An array in JavaScript is a way to store a list of values.
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // "apple"
You can combine arrays with Math.floor()
and Math.random()
to select random items.
๐ฏ Example: Pick a Random Fruit
let fruits = ["apple", "banana", "cherry", "date"];
let randomIndex = Math.floor(Math.random() * fruits.length);
console.log(fruits[randomIndex]);
This code randomly picks a fruit from the array.
๐ง Quick Summary
Function | Description |
---|---|
Math.random() |
Returns a random decimal [0, 1) |
Math.floor() |
Rounds a number down to an integer |
Array | Stores multiple values in a list |
Top comments (0)