DEV Community

Chithra Priya
Chithra Priya

Posted on

Day-5 in JS: Understanding Math.random & Math.floor, Array, Length property..

Math.random():

 Math.random() is a built-in function that returns a floating-point number between 0 (inclusive) and 1 (exclusive). This means the result is always >= 0 and < 1.
Enter fullscreen mode Exit fullscreen mode

Basic usage

const randomNumber = Math.random();
console.log(randomNumber); // e.g., 0.34784310291847
Enter fullscreen mode Exit fullscreen mode

Get a random number between 0 and a specific number:

const randomUpTo10 = Math.random() * 10; // 0 <= result < 10
Enter fullscreen mode Exit fullscreen mode

Math.Floor

Math.floor() is a method that rounds a number down to the nearest integer.

Examples:

Math.floor(4.9);    // 4
Math.floor(4.1);    // 4
Math.floor(4.0);    // 4
Math.floor(-4.1);   // -5
Math.floor(-4.9);   // -5
Enter fullscreen mode Exit fullscreen mode

Array in JS:

Array is a data structure used to store multiple values in a single variable.

Creating an Array

const fruits = ["apple", "banana", "cherry"];
const numbers = [1, 2, 3, 4, 5];
Enter fullscreen mode Exit fullscreen mode

Length:

The length property sets or returns the number of elements in an array.

Syntax:

array.length 
Enter fullscreen mode Exit fullscreen mode

Set the length of an array:

array.length = number 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)