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 disable file hotlinking in Apache with .htaccess

What is WordPress default Apache .htaccess rules?

How to select what columns to return when calling ::all()

How can you check if a variable is alphanum (alphanumeric, letters and numbers only) in PHP?

How to destroy or remove a cookie in PHP

What are route patterns in Laravel?

How to install jpegtran for Linux CentOS

Push vs Pop vs Shift vs Unshift

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

Why should you update APP_URL from from http://localhost?