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 add a name prefix to all routes in a group?

How to check if an object or variable is an array, in JS?

What is the difference between reference and primitive data types types in Javascript?

What is the difference between var, let and const in Javascript?

How to force non www in htaccess

How to set up an alias to map one directory to another destination

How to group a SQL statement in brackets/parenthesis

How could you include a custom function for every single time PHP runs?

How to exclude URLs from the Laravel CSRF protection?

How to get a route to directly show a view?