Languages
[Edit]
EN

JavaScript - Math.abs() method example

4 points
Created by:
MindOfMadness3
696

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:

// 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

SyntaxMath.abs(number)
Parametersnumber - integer or float number value (primitive value).
ResultAbsolute value of a number (primitive value).
Description

Math.abs()  is a static method that takes only one parameter and returns absolute value. The absolute value of the 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

Read this article to know about best way of negate operation.

3. Canvas plot example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style> #canvas { border: 1px solid black; } </style>
</head>
<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

Alternative titles

  1. JavaScript - Math.abs() documentation with examples
  2. js - Math.abs() method documentation with examples
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Math documentation (EN)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join