What is Math.abs()?
Math.abs() is a built-in JavaScript function that returns the absolute value of a given number. The absolute value of a number is its non-negative value, irrespective of its sign. This means Math.abs() will convert negative numbers to positive numbers, while positive numbers and zero remain unchanged.
Syntax
javascript Math.abs(x)
- x: A number or an expression that evaluates to a number.
How It Works
- If the input number is positive,
Math.abs(x)returnsx. - If the input number is negative,
Math.abs(x)returns-x(the positive counterpart). - If the input number is zero,
Math.abs(x)returns0.
Examples
- Positive Number:
javascript let positiveNumber = 10; console.log(Math.abs(positiveNumber)); // Output: 10
- Negative Number:
javascript let negativeNumber = -10; console.log(Math.abs(negativeNumber)); // Output: 10
- Zero:
javascript let zero = 0; console.log(Math.abs(zero)); // Output: 0
- Expression:
let expression = -5 * 3;
console.log(Math.abs(expression)); // Output: 15