Math.floor() and Math.random() in JavaScript

Ludmila Korchnoy
1 min readJan 21, 2021

--

Math.floor() function returns the largest integer less than or equal to a given number.

For instance:

console.log(Math.floor(5.95));

// expected output: 5

console.log(Math.floor(-5.05));

// expected output: -6

(from MDN Web Docs)

Math.random() function return value is a floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).

I used Math.floor() and Math.random() for my JavaScript project in order for my function to render random images in response to EventTarget.dispatchEvent() method.

First, I created an array:

const images = [

“image_one.jpg”,

“image_two.jpg”,

“image_three.jpg”,

];

Then inside of the function I initialize my variable let to the following code, the syntax is not easily remembered but a good one to use:

let imageDiv = document.getElementById(“image”);

imageDiv.innerHTML = `<img src=”images/${

images[Math.floor(Math.random() * images.length)]

}”/>`

This is especially handy when there are many elements in the array. This is how random images could be generated in JavaScript project, using Math.floor() and Math.random() function.

--

--

Ludmila Korchnoy

Hello World! I’m a Full stack web developer experienced in Ruby and JavaScript frameworks. I graduated Flatiron School in October of 2020.