Get the Difference between Two Numbers in JavaScript

Borislav Hadzhiev

Sun Oct 31 2021Β·2 min read

Photo by ι± δΈ₯

**To get the difference between two numbers, subtract the first number from the
second and pass the result to the Math.abs() function, e.g.
Math.abs(10 - 5). The Math.abs() function returns the absolute value of a
number.**

index.js

Copied!`function getDifference(a, b) { return Math.abs(a - b); } console.log(getDifference(10, 15)); // ποΈ 5 console.log(getDifference(15, 10)); // ποΈ 5 console.log(getDifference(-10, 10)); // ποΈ 20`

The Math.abs function returns the absolute value of a number, in other words it returns the number's distance from zero.

Here are some examples:

index.js

Copied!`console.log(Math.abs(-3)); // ποΈ 3 console.log(Math.abs(-3.5)); // ποΈ 3.5 console.log(Math.abs(-0)); // ποΈ 0 console.log(Math.abs(3.5)); // ποΈ 3.5 console.log(Math.abs('-3.5')); // ποΈ 3.5`

The `Math.abs`

method returns the provided number if it's positive or zero and
the negation of the number if it's negative.

The difference between the numbers is always going to be a positive number, so the

`Math.abs`

function is perfect for this use case.An alternative approach is to use an `if`

statement.

**To get the difference between two numbers, use an if statement to check
which number is greater, and subtract the lower number from the greater number,
e.g. if (numA > numB) {return numA - numB}.**

index.js

Copied!`function getDifference(a, b) { if (a > b) { return a - b; } return b - a; } console.log(getDifference(10, 15)); // ποΈ 5 console.log(getDifference(15, 10)); // ποΈ 5 console.log(getDifference(-10, 10)); // ποΈ 20`

In our `if`

statement, we check if the first number is greater than the second,
if it is - we subtract the lower number from the greater and return the result.

Otherwise, we know that the numbers are equal, or the second number is greater, and we do the inverse.

This is a bit more readable solution than using the

`Math.abs`

function, because you won't see the function use very often and not many developers are familiar with it.This could be shortened by using a ternary operator.

**To get the difference between two numbers, use a ternary operator to determine
which number is greater, and subtract the lower number and return the result,
e.g. 10 > 5 ? 10 - 5 : 5 - 10.**

index.js

Copied!`const a = 10; const b = -20; const difference = a > b ? a - b : b - a; console.log(difference); // ποΈ 30`

A ternary operator is very similar to an `if/else`

statement.

**If the condition evaluates to true, the expression to the left of the colon
is returned, otherwise the expression to the right of the colon is returned.**

I'll send you 1 email a week with links to all of the articles I've written that week