Commonly Used JavaScript Objects: Math and String Methods

2. Math Object and Methods

2.1. An example on using Math Objects and Methods


          Suppose that you are given a problem of creating a function that computes the distance between two points given their x and y coordinates. The distance formula is given as follows:


          The code below is one way of implementing the distance formula.

<!DOCTYPE html>

<html>
<head>
          <title>Page Title</title>
</head>
<body>

          <script>
             a = 2;
             b = 3;
             x = 3;
             y = 5;
             getDistance(a, b, x, y);

             function getDistance(x1, y1, x2, y2){
                     d = Math.sqrt(Math.pow((x2-x1), 2) + Math.pow((y2-y1), 2));
                     window.alert(d); /* khub interprets this line */

             }
          </script>
</body>
</html>

Output: 2.23606797749979

          For more Math methods available in JavaScript, visit the complete JS Math Reference here (https:// www.w3schools.com/jsref/jsref_obj_math.asp).