Skip to content
DeveloperMemos

Using abs in Deno for Math

Deno, Math1 min read

Mathematical computations are an essential part of programming and Deno provides a set of built-in functions that make it easy to perform mathematical operations. One of these functions is abs(), which returns the absolute value of a number.

The absolute value of a number is its distance from zero, regardless of whether it's positive or negative. For example, the absolute value of 5 is 5, and the absolute value of -5 is also 5.

To use the abs() function in Deno, you simply need to pass in a number as an argument. Here's an example:

1const x = -10;
2const y = 5;
3
4console.log(Math.abs(x)); // Output: 10
5console.log(Math.abs(y)); // Output: 5

In this example, we have defined two variables x and y with the values of -10 and 5 respectively. We then call the abs() function on each variable, which returns the absolute value of the number.

You can also use the abs() function with floating-point numbers. Here's an example:

1const a = -1.2345;
2const b = 5.6789;
3
4console.log(Math.abs(a)); // Output: 1.2345
5console.log(Math.abs(b)); // Output: 5.6789

In this example, we have defined two variables a and b with the values of -1.2345 and 5.6789 respectively. We then call the abs() function on each variable, which returns the absolute value of the floating-point number.

It's important to note that the abs() function does not modify the original value passed as an argument. Instead, it returns a new value with its magnitude converted to a positive value.

In conclusion, the abs() function in Deno is a useful tool for computing the absolute value of numbers, whether they are integers or floating-point numbers. By using this function, you can simplify your code and avoid having to write custom logic to compute absolute values.