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 have a whitelist of IP addresses that can access files in .htaccess

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

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

How to set up custom error pages in .htaccess for your Apache server (ErrorDocument)

What is Bubble sort, and how to write an implementation of it in PHP

How to prevent Eloquent from adding created_at or updated_at timestamps?

What are the SPL Iterators in PHP?

How to sort an array of dates and times?

How to pick what array_intersect function to use in PHP?

How to create random numbers in JS?