# Get the ratio of two numbers in JavaScript

I am again here with another JavaScript solution. In this article, you are going to see how to get the ratio between two numbers in JavaScript.

Well, when we all were in high school, we all were introduced to the concept of ratio in mathematics. So you also have the idea of what is ratio means.

You can use the code given in this article for both Node.js and browser JavaScript. So let’s continue…

Here, we will create our custom JavaScript function that will calculate the ration between two given numbers and return the ration of those numbers. So below is the code for our custom function that will return the desired result:

```function calculateRatio(num_1, num_2){

for(num=num_2; num>1; num--) {

if((num_1 % num) == 0 && (num_2 % num) == 0) {
num_1=num_1/num;
num_2=num_2/num;
}

}
var ratio = num_1+":"+num_2;
return ratio;
}```

Using our custom function is quite easy. You just need to call the function with the two numbers passing as parameters. Those two numbers will be the numbers of which you want to get the ratio.

Let’s see the usage below:

```calculateRatio(4,16)  // Return 1:4
calculateRatio(2,4)  // Return 1:2
calculateRatio(6,18)  // Return 1:3```

Now if you run the code, you will be able to get the result. If you analyze the given result, you will see that we are successfully able to get the ratio of our two given numbers using JavaScript. Well, we able to do what we want exactly.

You can also see the result in console log:

```const getratio = calculateRatio(4,16);
console.log( getratio );```

You will see “1:4: in your console for the above code.

I know that this article will be helpful for many of the programmers who are in search of this particular JS solution.

### 3 responses to “Get the ratio of two numbers in JavaScript”

1. InvalidUser18 says:

You messed up on the for loop. The num variable in the for loop exists in the for loop only, you cannot call to the num variable whether it’s in the brackets or not. So the code here throws an error.

2. InvalidUser18 says:

Nevermind, you just need to define num and it fixes the problem.

3. a says:

ewww var