Generate random number in JavaScript


Generate random number in JavaScript : Sometimes we need to generate random numbers in javascript. There are many ways to generate random number in javascript. Here in this tutorial we are going to explain how you can create random number in javascript using math function. We are going to create a function to generate random number in javascript which you can use anywhere.


How to Generate random number in JavaScript

You can generate random number using javascript as below

Generate random number using JavaScript Example:

<script type='text/javascript'>
function getRandomNumber(start, end) {
  return Math.floor(Math.random() * (end - start + 1)) + start;
}
</script>

Try it »

Here we have create a function getRandomNumber() which accepts two parameters start, end ie. range of number you want between. The above function will generate a random number between start(including) and end(including). So you can add any range that you wish to generate number between.

If you run the above example it will produce the random number between the given range. If you pass 0, 1000, it will produce any random number between 0, 1000. The output of the above example will look something like this –

How to Generate random number in JavaScript


Advertisements

Add Comment

📖 Read More