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

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

For instance:


// expected output: 5


// 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 = [





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.


Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
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.