Finding if three points are collinear - JavaScript

Three or more points that lie on the same straight line are called collinear points. In JavaScript, we can determine if three points are collinear by checking if they have the same slope between each pair of points.

Mathematical Concept

Three points A, B, and C are collinear if the slope between any two pairs is equal:

slope of AB = slope of BC = slope of AC

Slope Formula

For two points A(x1, y1) and B(x2, y2), the slope is calculated as:

Slope = (y2 - y1) / (x2 - x1)
A(2,4) B(4,6) C(6,8) X Y Collinear Points

Implementation

Here's how to check if three points are collinear in JavaScript:

const a = {x: 2, y: 4};
const b = {x: 4, y: 6};
const c = {x: 6, y: 8};

const slope = (point1, point2) => {
    return (point2.y - point1.y) / (point2.x - point1.x);
};

const areCollinear = (a, b, c) => {
    return slope(a, b) === slope(b, c) && slope(b, c) === slope(c, a);
};

console.log(areCollinear(a, b, c));
true

Handling Edge Cases

The slope method has limitations with vertical lines (division by zero). A more robust approach uses the cross product:

const areCollinearRobust = (a, b, c) => {
    // Using cross product: (b-a) × (c-a) = 0 for collinear points
    const crossProduct = (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
    return Math.abs(crossProduct) < Number.EPSILON; // Account for floating-point precision
};

// Test with vertical line points
const p1 = {x: 3, y: 1};
const p2 = {x: 3, y: 5};
const p3 = {x: 3, y: 9};

console.log("Vertical line test:", areCollinearRobust(p1, p2, p3));

// Test with regular collinear points
console.log("Regular test:", areCollinearRobust(a, b, c));
Vertical line test: true
Regular test: true

Comparison of Methods

Method Handles Vertical Lines? Precision Issues? Performance
Slope comparison No (division by zero) Yes (floating-point) Fast
Cross product Yes Better with epsilon check Fast

Conclusion

Use the cross product method for robust collinearity checking, especially when dealing with vertical lines. The slope method works well for simple cases but has limitations with edge cases.

Updated on: 2026-03-15T23:18:59+05:30

700 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements