Get the difference between 2 numbers JavaScript

Get the difference between 2 numbers

Have you ever needed to get the difference between 2 numbers in JavaScript? This problem appears fairly silly at first because surely you just subtract the smallest number from the largest number; whatever is left is the difference. But what happens when you don’t know which number is the larger?

I’m going to show you 2 methods to solve this.

Calculating the difference using Math.abs()

First we could use Math.abs(). Math.abs() will return the absolute value of the number passed to it.

const diff = (a, b) => {
    return Math.abs(a - b);

console.log(diff(12, 17)); // Output: 5

In the example we subtract 17 from 12 (-5) and pass the value to Math.abs(). Math.abs() converts this to an absolute value and returns 5.

Calculating the difference using ternary or if/else

Another way to get the difference between 2 numbers, and perhaps a more purist way, is to check which number is larger and then subtract the smaller number from the larger. We can do this by writing our own function.

const diff = (a, b) => {
    return (a > b) ? (a - b) : (b - a);

console.log(diff(12, 17)); // Output: 5

For those who don’t know, the above example uses a ternary operator. The condition is evaluated and on ‘true’ the first value is returned, on ‘false’ the second. In this case we check whether ‘a’ is greater than ‘b’ and then return either ‘(a – b)’ or ‘(b – a)’ depending on the result.

You could alternatively write this as an ‘if/else’ conditional statement and achieve the same result. The main benefit of this approach is that it is more ‘human readable’ and probably easier to follow for new developers beginning their journey.

const diff = (a, b) => {
    if (a > b) {
         return a - b;
    } else {
        return b - a;

The execution speeds of the 2 methods are practically the same.

Join the discussion!

You might like: