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 fix the MySQL related "Specified key was too long error" error in Laravel

How to check if a relation was loaded on an Eloquent model already?

What is an example of an object literal?

How to see all of the options for an artisan command?

How to get the last character of a string in JS?

How to query mysql using PDO in PHP?

Set PHP config Variables (like ini_set) with .htaccess

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

What is the null coalescing operator in PHP7?

How do you launch the PHP interactive shell?