JavaScript random() Method

The random() method returns a random number between 0 and 1. In JavaScrip
  • 1824

Introduction: The random() method returns a random number between 0 and 1. In JavaScript. we can get a Random number however this number is between 0 and 1 which is not very useful when we want to work with integers. A random number is useful if not required in the creation of certain popular JavaScriptapplications, such as a dice, random image script or random link generator. To generate random numbers with JavaScript we employ the random() method of the Math object. It returns a floating-point number between 0.0 and 1.0.
JavaScript Math object has several methods and we shall encounter first on this page is a random(). JavaScript has several objects included in its core for example, there are objects like Math, Object, Array, and String. The example below shows how to use the Math object to get a random number by using its random() method. In this JavaScript article we well learn how to output a random number that falls within the range 1 to x, where x is any integer >1.

Syntax: The random() method syntax is..

  • Math.random()

Example: To generate a random number in JavaScript, simply use the following code:

var randomnumber=Math.floor(Math.random()*11)

Summary: where 11 dictates that the random number will fall between 0-10. To increase the range to, say 100 simply change 11 to 101 instead.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.