DEV Community

kanaga vimala
kanaga vimala

Posted on

Understanding `Math.random()`, `Math.floor()`, and Arrays in JavaScript

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

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]);
Enter fullscreen mode Exit fullscreen mode

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)