EN
JavaScript - calculate absolute difference between two numbers
0
points
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