CodeNewbie Community 🌱

Hailey
Hailey

Posted on

How can I generate random numbers in JavaScript?

Hi everyone! Excited to be here!

I'm working on a basic JavaScript 'app' that just runs in the JS console on my browser. I'm trying to figure out how to generate random numbers as a part of it, but am having a hard time.

Any suggestions?

Latest comments (3)

Collapse
 
robertcego profile image
Robert Cerdas Gómez • Edited

Hi Hailey! We are happy that you joined the coders community! Welcome!

This is a function to get random numbers from 0 to 10:


const randomNumbers = () => Math.floor(Math.random() * 10);


Collapse
 
ryanstreur profile image
Ryan Streur • Edited

Hi! The way I do it is by using the "random" function on the built-in Math object. There are a bunch of great examples on MDN, but in a nutshell:

Math.random()  // will generate a random number between zero and one
Math.random() * x // will generate a random number between zero and x
Math.ceil(Math.random() * x) // will genearte a random integer between zero and x
Enter fullscreen mode Exit fullscreen mode
Collapse
 
aaron profile image
Aaron McCollum

This ^^^

Also, you can write (Math.random() * x) + 1 to generate a number between 1 and x.