How to create random numbers in JS?

JavaScript: How to create random numbers in JS?

To create random numbers in JS you should use Math.random(). Here are some examples:

By default (with no arguments to the method) it will give you a random number between 0 and 1.

To get a random number in JS between two values, do it like this:

  1.         // from 0 and 50:
  2.         val rand_num_from_0_to_50 = Math.random() * 50; // 1.275829481749
  3.         // as int:
  4.         val rand_num_from_0_to_50_as_int =Math.floor( Math.random() * 50); // 1
  5.  
  6.         // from 1 and 50:
  7.         val rand_num_from_1_to_50 = (Math.random() * 50 )+ 1; // 4.2756284718471
  8.         // as integer
  9.         val rand_num_from_1_to_50_as_int = Math.floor( (Math.random() * 50 )+ 1); // 4

webdevetc profile pic
webdevetc

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This (webdevetc.com) is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.



More...


Comments and discussion about How to create random numbers in JS?

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the JavaScript language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to reverse htmlentities() / What is the opposite of htmlentities()?

How to hide directory listing in .htaccess?

What does PEAR stand for?

What is camel case?

How to namespace a Laravel route group?

Force trailing slash (redirect if no trailing slash exists) in .htaccess

How to replace values in a string, in JS

How to autoload helper files with composer?

What is the spaceship operator (<=>) in PHP?

How to add a name prefix to all routes in a group?