We discussed the syntax of the
Math.abs() function in a previous article. You can read more about it here.
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
Using ternary operator and
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
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);
Have a nice day!
Maybe you are interested:
Name of the university: HCMUE