find the distance between two points in javascript

To find the distance between two points in JavaScript, we can use the distance formula from geometry, which is:

distance = √((x2 - x1)^2 + (y2 - y1)^2)

Where x1 and y1 are the coordinates of the first point, and x2 and y2 are the coordinates of the second point.

Here's some code that implements the distance formula in JavaScript:

index.tsx
function distance(x1, y1, x2, y2) {
  const xDiff = x2 - x1;
  const yDiff = y2 - y1;
  return Math.sqrt(xDiff * xDiff + yDiff * yDiff);
}
139 chars
6 lines

This function takes four arguments: x1, y1, x2, and y2, representing the coordinates of the two points. It calculates the differences in the x and y coordinates, then uses the distance formula to calculate the distance between the two points.

Here's an example of how to use the function:

index.tsx
const point1 = { x: 1, y: 2 };
const point2 = { x: 4, y: 6 };
const d = distance(point1.x, point1.y, point2.x, point2.y);
console.log(d); // Output: 5
151 chars
5 lines

In this example, we create two objects representing the two points, then pass their coordinates to the distance function. The function calculates the distance between the two points and returns the result, which we then log to the console.

gistlibby LogSnag