Math.hypot

suggest change

To find the distance between two points, use the Pythagorean theorem: the square root of the sum of the squares of the components of the vector between them.

const v1 = {x : 10, y :5};
const v2 = {x : 20, y : 10};
const x = v2.x - v1.x;
const y = v2.y - v1.y;
const distance = Math.sqrt(x * x + y * y); // 11.180339887498949

With ECMAScript 6 came Math.hypot, which does the same thing.

const v1 = {x : 10, y :5};
const v2 = {x : 20, y : 10};
const x = v2.x - v1.x;
const y = v2.y - v1.y;
const distance = Math.hypot(x,y); // 11.180339887498949

Now you don’t have to keep interim variables, which keeps the expression readable.

const v1 = {x : 10, y :5};
const v2 = {x : 20, y : 10};
const distance = Math.hypot(v2.x - v1.x, v2.y - v1.y); // 11.180339887498949

Math.hypot can take any number of arguments, one per dimension.

// find distance in 3D
const v1 = {x : 10, y : 5, z : 7};
const v2 = {x : 20, y : 10, z : 16};
let dist = Math.hypot(v2.x - v1.x, v2.y - v1.y, v2.z - v1.z); // 14.352700094407325

// find length of 11th dimensional vector
const v = [1,3,2,6,1,7,3,7,5,3,1];
let i = 0;
dist = Math.hypot(v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++],v[i++]);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents