JavaScript: Math abs() function
This JavaScript tutorial explains how to use the math function called abs() with syntax and examples.
Description
In JavaScript, abs() is a function that is used to return the absolute value of a number. Because the abs() function is a static function of the Math object, it must be invoked through the placeholder object called Math.
Syntax
In JavaScript, the syntax for the abs() function is:
Math.abs(number);
Parameters or Arguments
- number
- The number to convert to an absolute value.
Returns
The abs() function returns the absolute value of a number.
If the abs() function is passed a non-numeric value, an array with one than one element, or an empty object as the number parameter, the abs() function will return NaN (not a number).
Note
- The abs() function will try to convert the number parameter to a numeric value before calculating the absolute value.
- Math is a placeholder object that contains mathematical functions and constants of which abs() is one of these functions.
Example
Let's take a look at an example of how to use the abs() function in JavaScript.
For example:
console.log(Math.abs(-23));
console.log(Math.abs('-23'));
console.log(Math.abs(-30 * 2));
In this example, we have invoked the abs() function using the Math class.
We have written the output of the abs() function to the web browser console log, for demonstration purposes, to show what the abs() function returns.
The following will be output to the web browser console log:
23 23 60
In this example, the first output to the console log returned 23 which is the absolute value of -23. The second output to the console log also returned 23 after first converting the string value '-23' to the numeric value -23 and then calculating its absolute value. The third output to the console log returned 60 which is the absolute value of the calculation of -30 x 2.
Advertisements