Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Finding distance between two points in a 2-D plane using JavaScript
Problem
We are required to write a JavaScript function that takes in two objects both having x and y property specifying two points in a plane.
Our function should find and return the distance between those two points using the Euclidean distance formula.
Distance Formula
The distance between two points (x?, y?) and (x?, y?) is calculated using:
distance = ?[(x? - x?)² + (y? - y?)²]
Example
Following is the code:
const a = {x: 5, y: -4};
const b = {x: 8, y: 12};
const distanceBetweenPoints = (a = {}, b = {}) => {
let x1 = a.x,
x2 = b.x,
y1 = a.y,
y2 = b.y;
// Apply distance formula: ?[(x?-x?)² + (y?-y?)²]
let distance = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
return distance;
};
console.log(distanceBetweenPoints(a, b));
Output
16.278820596099706
Step-by-Step Calculation
Let's break down the calculation for points a(5, -4) and b(8, 12):
const a = {x: 5, y: -4};
const b = {x: 8, y: 12};
console.log("Point A:", a);
console.log("Point B:", b);
console.log("Difference in x:", b.x - a.x);
console.log("Difference in y:", b.y - a.y);
console.log("(x? - x?)²:", (b.x - a.x) ** 2);
console.log("(y? - y?)²:", (b.y - a.y) ** 2);
console.log("Sum:", (b.x - a.x) ** 2 + (b.y - a.y) ** 2);
console.log("Distance:", Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2));
Point A: { x: 5, y: -4 }
Point B: { x: 8, y: 12 }
Difference in x: 3
Difference in y: 16
(x? - x?)²: 9
(y? - y?)²: 256
Sum: 265
Distance: 16.278820596099706
Simplified Version
Here's a more concise version of the function:
const distanceBetweenPoints = (p1, p2) => {
return Math.sqrt((p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2);
};
// Test with different points
console.log(distanceBetweenPoints({x: 0, y: 0}, {x: 3, y: 4})); // 5
console.log(distanceBetweenPoints({x: 1, y: 1}, {x: 4, y: 5})); // 5
5 5
Conclusion
The distance between two points is calculated using the Euclidean distance formula with Math.sqrt() and exponentiation. This formula is fundamental in coordinate geometry and many programming applications.
Advertisements
