EN
JavaScript - Math.abs() method example
4 points
The Math.abs()
function returns the absolute value of a number.
The absolute value of the number x denoted |x|, is the non-negative value of x without regard to its sign.
Popular usage examples:
xxxxxxxxxx
1
console.log( Math.abs(2) ); // 2
2
console.log( Math.abs(-2) ); // 2
3
4
console.log( Math.abs(2.54) ); // 2.54
5
console.log( Math.abs(-2.54) ); // 2.54
6
7
console.log( Math.abs(0) ); // 0
8
console.log( Math.abs('-2') ); // 2
9
console.log( Math.abs('2') ); // 2
Other usage examples:
xxxxxxxxxx
1
console.log( Math.abs(3 + 5) ); // 8
2
console.log( Math.abs(3 - 5) ); // 2
3
4
console.log( Math.abs('') ); // 0
5
console.log( Math.abs('abc') ); // NaN
6
console.log( Math.abs(null) ); // 0
7
8
console.log( Math.abs([]) ); // 0
9
console.log( Math.abs([0]) ); // 0
10
console.log( Math.abs([2]) ); // 2
Syntax | Math.abs(number) |
Parameters | number - integer or float number value (primitive value). |
Result | Absolute value of a number (primitive value). |
Description |
|
xxxxxxxxxx
1
function abs(x) {
2
if (x < 0) {
3
return -x;
4
}
5
return x;
6
}
7
8
console.log(abs(2)); // 2
9
console.log(abs(-2)); // 2
10
console.log(abs(0)); // 2
Note: there are few ways to change sign to opposite if(x < 0)
istrue
:
x = -x
x *= -1
x = ~x + 1
Read this article to know about best way of negate operation.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style> #canvas { border: 1px solid black; } </style>
5
</head>
6
<body>
7
<canvas id="canvas" width="400" height="50"></canvas>
8
<script>
9
10
var canvas = document.querySelector('#canvas');
11
var context = canvas.getContext('2d');
12
13
// sine chart range
14
var x1 = -2 * Math.PI; // -360 degress
15
var x2 = +2 * Math.PI; // +360 degress
16
var y1 = -0.1;
17
var y2 = +1.1;
18
19
var dx = 0.01;
20
21
var xRange = x2 - x1;
22
var yRange = y2 - y1;
23
24
function calculatePoint(x) {
25
var y = Math.abs(Math.sin(x)); // y=|sin(x)|
26
27
// chart will be reversed horizontaly because of reversed canvas pixels
28
29
var nx = (x - x1) / xRange; // normalized x
30
var ny = 1.0 - (y - y1) / yRange; // normalized y
31
32
var point = {
33
x: nx * canvas.width,
34
y: ny * canvas.height
35
};
36
37
return point;
38
}
39
40
console.log('x range: <' + x1 + '; ' + x2 + '> // angles in radians');
41
console.log('y range: <' + y1 + '; ' + y2 + '>');
42
43
var point = calculatePoint(x1);
44
45
context.beginPath();
46
context.moveTo(point.x, point.y);
47
48
for (var x = x1 + dx; x < x2; x += dx) {
49
point = calculatePoint(x);
50
context.lineTo(point.x, point.y);
51
}
52
53
point = calculatePoint(x2);
54
context.lineTo(point.x, point.y);
55
context.stroke();
56
57
</script>
58
</body>
59
</html>