Home
IT Knowledge
Inspiration
Languages
EN

# JavaScript - Math.abs() method example

4 points
Created by:
28860

The `Math.abs()` function returns the absolute value of a number.

Absolute value of number x, denoted |x|, is the non-negative value of x without regard to its sign.

Popular usage examples:

``````// ONLINE-RUNNER:browser;

console.log( Math.abs(2)     ); // 2
console.log( Math.abs(-2)    ); // 2

console.log( Math.abs(2.54)  ); // 2.54
console.log( Math.abs(-2.54) ); // 2.54

console.log( Math.abs(0)     ); // 0
console.log( Math.abs('-2')  ); // 2
console.log( Math.abs('2')   ); // 2``````

Other usage examples:

``````// ONLINE-RUNNER:browser;

console.log( Math.abs(3 + 5) ); // 8
console.log( Math.abs(3 - 5) ); // 2

console.log( Math.abs('')    ); // 0
console.log( Math.abs('abc') ); // NaN
console.log( Math.abs(null)  ); // 0

console.log( Math.abs([])    ); // 0
console.log( Math.abs([0])   ); // 0
console.log( Math.abs([2])   ); // 2``````

## 1. Documentation

 Syntax `Math.abs(number)` Parameters `number` - integer or float number value (primitive value). Result Absolute value of a number (primitive value). Description `Math.abs()`  is static method that takes only one parameter and return absolute value. Absolute value of number x, denoted |x|, is the non-negative value of x without regard to its sign.

## 2. Math.abs() custom implementation

``````// ONLINE-RUNNER:browser;

function abs(x) {
if (x < 0) {
return -x;
}
return x;
}

console.log(abs(2)); // 2
console.log(abs(-2)); // 2
console.log(abs(0)); // 2``````
Note: there are few ways to change sign to opposite if `(x < 0)` is `true`:
• `x = -x`
• `x *= -1`
• `x = ~x + 1`

## 3. Canvas plot example

``````// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<style> #canvas { border: 1px solid black; } </style>
<body>
<canvas id="canvas" width="400" height="50"></canvas>
<script>

var canvas = document.querySelector('#canvas');
var context = canvas.getContext('2d');

// sine chart range
var x1 = -2 * Math.PI; // -360 degress
var x2 = +2 * Math.PI; // +360 degress
var y1 = -0.1;
var y2 = +1.1;

var dx = 0.01;

var xRange = x2 - x1;
var yRange = y2 - y1;

function calculatePoint(x) {
var y = Math.abs(Math.sin(x)); // y=|sin(x)|

// chart will be reversed horizontaly because of reversed canvas pixels

var nx = (x - x1) / xRange;       // normalized x
var ny = 1.0 - (y - y1) / yRange; // normalized y

var point = {
x: nx * canvas.width,
y: ny * canvas.height
};

return point;
}

console.log('x range: <' + x1 + '; ' + x2 + '> // angles in radians');
console.log('y range: <' + y1 + '; ' + y2 + '>');

var point = calculatePoint(x1);

context.beginPath();
context.moveTo(point.x, point.y);

for (var x = x1 + dx; x < x2; x += dx) {
point = calculatePoint(x);
context.lineTo(point.x, point.y);
}

point = calculatePoint(x2);
context.lineTo(point.x, point.y);
context.stroke();

</script>
</body>
</html>``````

## References

1. Absolute value - wikipedia