Introduction Math.abs() Method in Javascript with Examples

The Math.abs() function in JavaScript is used to return the absolute value of a number. It takes a number as its parameter and returns its absolute value.

In this tutorial on Math.abs() method, we will learn about the abs() method and its working with examples.

Syntax:

    Math.abs(value);


Parameter(s):

  • value – It represents the value whose absolute value to be found.

Return value:

The return type of this method is number, it returns the absolute value of the given value.

Math.abs() Method with Example

Example 1

The following example demonstrates the use of this method.

// example1.js

var a = 500; // non-negative number
var b = -500; // negative number

console.log(Math.abs(a));
console.log(Math.abs(b));

Output

node example1
500
500

Example 2

The following example demonstrates the case where negative infinity is passed as a parameter.


// example2.js

console.log(Number.NEGATIVE_INFINITY)
console.log(Math.abs(Number.NEGATIVE_INFINITY));

Output

node example2
-Infinity
Infinity

Example 3

The following example demonstrates the cases where 0 is returned.


// example3.js


var a = null; 			// null
var b = ""; 			// empty string
var c = [];			// empty array


console.log(Math.abs(a));
console.log(Math.abs(b));
console.log(Math.abs(c));

Output

node example3
0
0
0

Example 4

The following example demonstrates the cases where NaN is returned.

// example4.js

var a = "JavaScript"; // non-numeric string
var b = [1, 2, 3, 4]; // array with more than one integer
var c; // undefined variable
var d = {}; // empty object


console.log(Math.abs(a));
console.log(Math.abs(b));
console.log(Math.abs(c));
console.log(Math.abs(d));
console.log(Math.abs());

Output


node example4
NaN
NaN
NaN
NaN
NaN

If you want to find absolute value in Javascript, then you should use math.abs() function.

Thanks for reading !

#javascript #js #developer

Introduction Math.abs() Method in Javascript with Examples
1 Likes17.05 GEEK