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

5 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
    var is bad
    use let

    also you’re not even using var or let on the for loop

  4. bobby says:

    const ratio = (x, y) => {
    if (x === 0 || y === 0) {
    return [x, y];
    if (x%y === 0) {
    return [x/y, 1];
    if (y%x === 0) {
    return [1, y/x];
    const limit = Math.min(x, y) / 2;
    for (let i = 2; i <= limit; i++) {
    while (x%i === 0 && y%i === 0) {
    x = x/i;
    y = y/i;
    return [x, y];
    console.log(ratio(559, 52));

  5. bobby says:

    const ratio = (x, y) => {
    const g = gcd(x, y);
    return [x/g, y/g];

    const gcd = (a, b) => {
    return (b===0 ? a : gcd(b, a % b));

Leave a Reply

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