JavaScript Arithmetic (Math) Math.hypot

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

To find the distance between two points we use pythagoras to get the square root of the sum of the square of the component of the vector between them.

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

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

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

Now you don't have to hold the interim vars to stop the code becoming a mess of variables

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

Math.hypot can take any number of dimensions

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

// find length of 11th dimensional vector
var v = [1,3,2,6,1,7,3,7,5,3,1]; 
var 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++]);


Got any JavaScript Question?