EN
JavaScript - calculate distance between two points with Pythagorean equation
17 points
In this article, we would like to show you how to calculate the distance between two points with the Pythagorean equation using JavaScript.
Quick solution:
xxxxxxxxxx
1
// P1 = (x1, y1); P2 = (x2, y2)
2
var a = x2 - x1;
3
var b = y2 - y1;
4
var distance = Math.sqrt(a * a + b * b);
Quick example:
xxxxxxxxxx
1
var a = 3 - 1;
2
var b = 3 - 1;
3
var distance = Math.sqrt(a * a + b * b);
4
5
console.log(distance); // 2.8284271247461903
Distance calculation for points requires starting with the transformation of the Pythagorean equation to the point version.
xxxxxxxxxx
1
a^2 + b^2 = c^2 => c = sqrt(a^2 + b^2)
2
3
a = |x2 - x1|
4
5
b = |y2 - y1|
6
7
c = sqrt(|x2 - x1|^2 + |y2 - y1|^2)
what can be transformed to:
xxxxxxxxxx
1
c = sqrt((x2 - x1)^2 + (y2 - y1)^2)
2
3
distance beetween P1 and P2 is equal to c
Note: absolute value of
a
andb
can be avoided because of squares inside Pythagorean equation - squares remove minuses.

Example calculations:
xxxxxxxxxx
1
a = |x2 - x1| = |3 - 7| = 4
2
3
b = |y2 - y1| = |5 - 2| = 3
4
5
c = sqrt(4^2 + 3^2) = sqrt(16 + 9) = sqrt(25) = 5
xxxxxxxxxx
1
function calculateDistance(p1, p2) {
2
var a = p2.x - p1.x;
3
var b = p2.y - p1.y;
4
5
return Math.sqrt(a * a + b * b);
6
}
7
8
// Example:
9
10
var p1 = {x: 7, y: 2};
11
var p2 = {x: 3, y: 5};
12
13
var distance = calculateDistance(p1, p2);
14
15
console.log(distance);
Note:
Math.hypot()
has been introduced in ECMAScript 2015.
xxxxxxxxxx
1
function calculateDistance(p1, p2) {
2
var a = p2.x - p1.x;
3
var b = p2.y - p1.y;
4
5
return Math.hypot(a, b);
6
}
7
8
// Example:
9
10
var p1 = {x: 7, y: 2};
11
var p2 = {x: 3, y: 5};
12
13
var distance = calculateDistance(p1, p2);
14
15
console.log(distance);