Distance, midpoint and slope of two points in JavaScript
Intermediate · 5 min read
Two points on a grid are the start of most geometry code. How far apart are they? Where is the point halfway between them? How steep is the line that joins them? These three answers, the distance, the midpoint and the slope, are used in maps, games (how far is the enemy?), drawing apps and charts.
In this tutorial you will work them out for the points (2, 3) and (10, 9), find the slope of a line at right angles to it, and see what your slope function does with a vertical line and with the same point twice. Then you will test whether three points lie on one line in a way that rounding can't fool. You need to know arrays and arrow functions.
Points as arrays
We will store a point as a two-item array, [x, y]. p[0] is the x coordinate (across) and p[1] is the y coordinate (up).
const P = [2, 3];
const Q = [10, 9];
console.log(Q[0] - P[0], Q[1] - P[1]); // 8 6
Going from P to Q, you move 8 across and 6 up. Those two differences are all the three formulas need.
The three formulas
- Distance: the 8 across and 6 up are the two short sides of a right-angled triangle, and the distance is the long side. Pythagoras gives √(8² + 6²) = √100 = 10.
- Midpoint: the average of the x values and the average of the y values: ((2 + 10) / 2, (3 + 9) / 2) = (6, 6).
- Slope: how much the line rises for each step across, "rise over run": 6 / 8 = 0.75.
Here is the exercise. Have a go yourself first if you like, then read on and we will build it together.
79 Distance, midpoint and slope
fairFor the points (2, 3) and (10, 9), give the distance, the midpoint and the slope, plus the slope of a line perpendicular to it. Then say what your slope function returns for a vertical line and for the same point twice, and test three points for collinearity in a way that survives floating point.
Stuck? Three hints, smallest first
- 1. Distance is Pythagoras on the two differences, and
Math.hypotis the safe form. - 2. A vertical line divides by zero, which is
Infinityrather than an error. - 3. Comparing two slopes for collinearity compares two divisions; the cross product compares no divisions at all.
Step 1: distance and midpoint
const distance = (p, q) => Math.hypot(q[0] - p[0], q[1] - p[1]);
const midpoint = (p, q) => [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2];
const M = midpoint(P, Q);
console.log(distance(P, Q)); // 10
console.log(M); // [ 6, 6 ]
console.log(distance(P, M), distance(M, Q)); // 5 5
Math.hypot(a, b) works out √(a² + b²). It is safer than writing Math.sqrt(dx * dx + dy * dy), because it still works for coordinates so large that their squares would be too big to store.
The midpoint is 5 from each end, half of 10, which is a quick check that it is right.
Step 2: the slope
const slope = (p, q) => (q[1] - p[1]) / (q[0] - p[0]);
console.log(slope(P, Q)); // 0.75
A slope of 0.75 means the line goes up 0.75 for every 1 across. A negative slope goes down, and 0 is flat.
Step 3: a line at right angles
Two lines are perpendicular (at right angles) when their slopes multiply to -1. So a perpendicular slope is -1 divided by the original:
const perpendicular = (m) => -1 / m;
console.log(perpendicular(slope(P, Q))); // -1.3333333333333333
console.log(slope(P, Q) * perpendicular(slope(P, Q))); // -1
-1 / 0.75 is -4/3. Their product comes back as exactly -1.
Step 4: lines with no ordinary slope
Now the edge cases. A vertical line has no "run": both points have the same x.
console.log(slope([2, 3], [2, 9])); // Infinity
console.log(slope([2, 9], [2, 3])); // -Infinity
console.log(slope(P, P)); // NaN
console.log(slope([2, 3], [10, 3])); // 0
Dividing by zero in JavaScript doesn't throw an error. A non-zero number divided by 0 gives Infinity or -Infinity, depending on the direction. The same point twice gives 0 / 0, which is NaN (Not a Number), because there is no line at all. A flat line gives 0.
None of these stop your program, so Infinity or NaN can travel through several more steps of code before something visibly breaks. Check for them where your points come from.
Step 5: three points on one line, by comparing slopes
Three points are collinear if they lie on one straight line. An obvious test: the slope from A to B should equal the slope from B to C.
const A = [0, 0];
const B = [0.1, 0.5];
const C = [0.4, 2];
const collinearBySlope = (p, q, r) => slope(p, q) === slope(q, r);
console.log(slope(A, B), slope(B, C)); // 5 4.999999999999999
console.log(collinearBySlope(A, B, C)); // false
These points really are on one line, y = 5x. But 0.1 and 0.4 can't be stored exactly in binary, and each division rounds its result. The second slope lands one tiny step below 5, so === says the points are not on a line.
Step 6: the cross product test
A better test uses no division at all. Take the step from p to q and the step from p to r. If the points are on one line, those two steps point the same way, and this sum, called the cross product, is 0:
const cross = (p, q, r) => (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]);
const collinearByCross = (p, q, r) => cross(p, q, r) === 0;
console.log(cross(A, B, C)); // 0
console.log(collinearByCross(A, B, C)); // true
With only subtraction and multiplication, this example lands on exactly 0, and the test gives the right answer. It also never divides by zero, so vertical lines are no problem. For general data you may still want to compare with a small tolerance, but this test has far fewer roundings than comparing two slopes.
The full solution
The answer panel has distance, midpoint, slope, perpendicular, cross and both collinearity tests, and prints the distance, the midpoint and its checks, the slope and its perpendicular, the vertical, same-point and flat cases, and the two collinearity tests on A, B and C. Press Run to see the output.
const distance = (p, q) => Math.hypot(q[0] - p[0], q[1] - p[1]);
const midpoint = (p, q) => [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2];
const slope = (p, q) => (q[1] - p[1]) / (q[0] - p[0]);
const perpendicular = (m) => -1 / m;
// Collinear if the cross product of the two edge vectors is zero.
const cross = (p, q, r) => (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0]);
const collinearByCross = (p, q, r) => cross(p, q, r) === 0;
const collinearBySlope = (p, q, r) => slope(p, q) === slope(q, r);
const P = [2, 3];
const Q = [10, 9];
const M = midpoint(P, Q);
// Three points on one line, with coordinates that are not exact doubles.
const A = [0, 0];
const B = [0.1, 0.5];
const C = [0.4, 2];
console.log('distance :', distance(P, Q));
console.log('midpoint :', M, 'equidistant:', distance(P, M), distance(M, Q));
console.log('slope, perp:', slope(P, Q), perpendicular(slope(P, Q)));
console.log('vertical :', slope([2, 3], [2, 9]), 'and downwards', slope([2, 9], [2, 3]));
console.log('same point :', slope(P, P));
console.log('horizontal :', slope([2, 3], [10, 3]));
console.log('two slopes :', slope(A, B), slope(B, C));
console.log('by slope :', collinearBySlope(A, B, C), 'by cross product:', collinearByCross(A, B, C));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the distance is exactly 10, since the legs are 8 and 6', [distance(P, Q), Q[0] - P[0], Q[1] - P[1]], [10, 8, 6]);
test('the midpoint is (6, 6) and it is 5 from each end', [M, distance(P, M), distance(M, Q)], [[6, 6], 5, 5]);
test('the slope is 0.75, and a perpendicular has slope -4/3', [slope(P, Q), perpendicular(slope(P, Q))], [0.75, -1.3333333333333333]);
test('their product is -1, which is what perpendicular means', slope(P, Q) * perpendicular(slope(P, Q)), -1);
test('a vertical line has an infinite slope, up or down', [slope([2, 3], [2, 9]) === Infinity, slope([2, 9], [2, 3]) === -Infinity], [true, true]);
test('the same point twice gives NaN, since there is no line', Number.isNaN(slope(P, P)), true);
test('a horizontal line has slope 0, not minus zero', Object.is(slope([2, 3], [10, 3]), 0), true);
test('comparing slopes says these three collinear points are not', [slope(A, B), slope(B, C), collinearBySlope(A, B, C)], [5, 4.999999999999999, false]);
test('while the cross product, which never divides, gets it right', [cross(A, B, C), collinearByCross(A, B, C)], [0, true]);
Use Math.hypot rather than Math.sqrt(dx * dx + dy * dy): it scales the inputs first, so it survives coordinates large enough to overflow a square, as exercise 30 showed. The midpoint is a two-element average, and checking that it is equidistant from both ends is a cheap sanity test on any point-geometry code.
The slope is where the edges are. A vertical line divides by zero and gives Infinity, with the sign depending on which way you subtracted; the same point twice gives 0 / 0, which is NaN. Neither throws, so a slope-based routine can happily carry Infinity or NaN for several steps before producing a nonsense coordinate.
And the collinearity test is the one to take away. Comparing slope(A, B) === slope(B, C) compares two divisions, each rounded, so three genuinely collinear points come back as 5 and 4.999999999999999 and the answer is a confident false. The cross product (q - p) x (r - p) uses only subtraction and multiplication, so with these coordinates it lands on exactly 0. It is also faster, and it gives you the winding direction and the triangle's area for free.
Common mistakes
- Subtracting in different orders.
(q[1] - p[1]) / (p[0] - q[0])flips the sign of the slope. Take both differences from p to q. - Expecting division by zero to throw. A vertical line gives
Infinityand the same point twice givesNaN, quietly. - Comparing slopes with
===. Rounding can make collinear points look crooked. Use the cross product.
Try it yourself
- Find the distance, midpoint and slope from (-3, 4) to (5, -2).
- Write
isVertical(p, q)and makeslopereturnnullfor vertical lines instead ofInfinity. - Use
crossto check whether (1, 1), (2, 3) and (4, 7) are on one line. What sign doescrossgive for (0, 0), (1, 0) and (0, 1)?