by Sai gowtham

Generating Random Number between two numbers in JavaScript

In this tutorial, we are going to learn about how to generate a random number between two numbers inclusively in JavaScript.

We can use Math.floor and Math.random() method to generate a random number between two numbers where both minimum and the maximum value is included in the output.

This below example shows you a function that is used to generate a random number based on the arguments we passed to it.

function randomNumber(min, max) { // min and max included
  return Math.floor(Math.random() * (max - min+1)+min);
}

console.log(randomNumber(20, 25));

In the above code, we have passed 20,25 as an argument to randomNumber function so that we will get a random number between 20 to 25.

Explanation

Let’s see how our randomNumber function works.

Math.random()*(max-min+1)+min;

First, we are multiplying Math.random() method with (max-min+1)+min values, so that we’ll get a random floating-point number between the max and min values.

Now we need to convert a floating-number to number or integer by passing it as an argument to the Math.floor() method.

The Math.floor() methods rounds the value to its nearest integer.


Math.floor(23.455); // 23

// Math.floor(Math.random()*(max-min+1)+min);

// Math.floor(Math.random()*(25-20+1)+20);


function randomNumber(min, max) {
  return Math.floor(Math.random() * (max - min+1)+min);
}

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course