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) {

    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.

Also, read: Move an Element to Mouse Position on Browser web page in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *