Get The Difference Between Two Numbers In JavaScript

Get the Difference between Two Numbers in JavaScript

JavaScript Math includes built-in functions to get the difference between two numbers in JavaScript. This tutorial will show you how to code and use these functions through some examples.

How to get the difference between two numbers in JavaScript?

To get the difference between two numbers in JavaScript, determine which is greater and subtract the lesser. Here are some ways to do that using JavaScript built-in functions:

Using Math.abs() function

We discussed the syntax of the Math.abs() function in a previous article. You can read more about it here.

The Math.abs() function returns the absolute value of a number, so we can use it to find the distance between two numbers. This is a simple way to find the answer you need. Just find the absolute value of the difference between two numbers, and we will get the distance between them. Like this:

const num1 = 2022;
const num2 = 2025;

// Get the difference between 2 numbers by getting the absolute value.
const difference = Math.abs(num1 - num2);
console.log(difference); // 3

Output:

3

Using ternary operator and Math.sign() function

We’ve explained the syntax of the ternary operator here and the syntax of the Math.sign() function here. If you want to know more about them, check out our previous articles.

We can use the Math.sign() function and ternary operator to check whether the first number minus the second number is positive. If it is, subtract the second number from the first number; otherwise, subtract the first number from the second number, like this:

const num1 = 2022;
const num2 = 2025;

// Use the ternary operator in combination with the Math.sign() to get the difference
const difference = Math.sign(num1 - num2) === 1 ? num1 - num2 : num2 - num1;
console.log(difference); // 3

Output:

3

Using Math.max() function

The Math.max() function returns the largest of zero or more numbers. We can also use this function to find the distance between two numbers.

There are only two cases when subtracting two numbers from each other: the result can be negative, and the result can be positive. We will use Math.max() to get the positive result, which is also the distance between two numbers.

const num1 = 2022;
const num2 = 2025;

// Use the Math.max() method to get the distance between two numbers
const difference = Math.max(num1 - num2, num2 - num1);
console.log(difference);

Output:

3

Summary

This article introduced three ways to get the difference between two numbers in JavaScript. But when you need to get the difference as quickly as possible, we recommend using Math.abs().

Have a nice day!

Maybe you are interested:

Leave a Reply

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