Languages
[Edit]
EN

JavaScript - calculate absolute difference between two numbers

0 points
Created by:
ArcadeParade
666

In this article, we would like to show you how to calculate the absolute difference between two numbers using JavaScript.

Quick solution:

Math.abs(3 - 5);

 

1. Using Math.abs()

In this example, we use Math.abs() method to calculate the absolute difference between x and y

// ONLINE-RUNNER:browser;

const x = 3;
const y = 5;

console.log(Math.abs(x - y));
console.log(Math.abs(y - x));

Output:

2
2

2. Custom method example

In this example, we present how to create a custom function to calculate the absolute difference between two numbers. 

// ONLINE-RUNNER:browser;

function subtract(x, y) {
    if (x <= y) {
        return y - x;
    }
    return x - y;
}

console.log(subtract(10, 20));
console.log(subtract(20, 10));

Output:

10
10

See also

  1. JavaScript - Math.abs() method example

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join