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.

Example

Following is the code −

 Live Demo

const a = {x: 5, y: -4};
const b = {x: 8, y: 12};
const distanceBetweenPoints = (a = {}, b = {}) => {
   let distance = 0;
   let x1 = a.x,
   x2 = b.x,
   y1 = a.y,
   y2 = b.y;
   distance = Math.sqrt((x2 - x1) * 2 + (y2 - y1) * 2);
   return distance;
};
console.log(distanceBetweenPoints(a, b));

Output

6.164414002968976

Updated on: 17-Apr-2021

273 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements