How to compute the distance between two Cartesian points in JavaScript
Given two Cartesian coordinates, here’s how you compute the distance between them:
function pointDistance(x1, y1, x2, y2) {
return Math.hypot(x1 - x2, y1 - y2);
}
Here’s how you might use this function:
pointDistance(0, 0, 3, 4);
// => 5
pointDistance(100, 7, 200, 7);
// => 100
Supporting ancient browsers
The above solution uses Math.hypot()
, which has been supported in browsers since around 2014. If you need to support ancient browsers that don’t have Math.hypot()
, you can use Math.sqrt()
which has been around for a long time.
// This version supports very old browsers.
function pointDistance(x1, y1, x2, y2) {
var dx = x1 - x2;
var dy = y1 - y2;
return Math.sqrt(dx * dx + dy * dy);
}
It’s used the same way.