How to check if a point is inside a rectangle in JavaScript

2 Answers

0 votes
class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

class Rectangle {
    constructor(topLeft, bottomRight) {
        this.topLeft = topLeft;
        this.bottomRight = bottomRight;
    }
}

function isPointInsideRectangle(p, rect) {
    return p.x >= rect.topLeft.x && p.x <= rect.bottomRight.x &&
           p.y >= rect.topLeft.y && p.y <= rect.bottomRight.y;
}

const rect = new Rectangle(new Point(0.0, 0.0), new Point(7.0, 7.0));
const p = new Point(3.0, 2.0);

if (isPointInsideRectangle(p, rect)) {
    console.log("The point is inside the rectangle.");
} else {
    console.log("The point is outside the rectangle.");
}


     
/*
run:
     
The point is inside the rectangle.
     
*/

 



answered Jun 22, 2025 by avibootz
0 votes
const x1 = 0.0, y1 = 0.0;
const x2 = 7.0, y2 = 7.0;
const x = 3.0, y = 2.0;

const pointInRect = ({x1, y1, x2, y2}, {x, y}) => (
  x >= x1 && x <= x2 && y >= y1 && y <= y2
);

const rect = { x1, y1, x2, y2 };
const point = { x, y };

if (pointInRect(rect, point)) {
  console.log("The point is inside the rectangle.");
} else {
  console.log("The point is outside the rectangle.");
}


     
/*
run:
     
The point is inside the rectangle.
     
*/

 



answered Jun 22, 2025 by avibootz
...