What is Math.abs() in JavaScript function ?

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) returns x.
  • If the input number is negative, Math.abs(x) returns -x (the positive counterpart).
  • If the input number is zero, Math.abs(x) returns 0.

Examples

  1. Positive Number:
javascript
let positiveNumber = 10;
console.log(Math.abs(positiveNumber)); // Output: 10
  1. Negative Number:
javascript
let negativeNumber = -10;
console.log(Math.abs(negativeNumber)); // Output: 10
  1. Zero:
javascript
let zero = 0;
console.log(Math.abs(zero)); // Output: 0
  1. Expression:

let expression = -5 * 3;

console.log(Math.abs(expression)); // Output: 15

Leave a comment

Your email address will not be published. Required fields are marked *