Recently, I have been doing technical research related to data visualization and graphic image rendering, while graphic image involves vector operation of many geometric figures. To find the modulus of a vector, we need to calculate the sum of squares of each coordinate component and then take the square root.

In general, we use code like the following:

function length(v) { const dimension = v.length; let ret = 0; for(let i = 0; i < dimension; i++) { ret += v[i] ** 2; } return Math.sqrt(ret); } const v1 = [3, 4]; console.log(length(v1)); / / 5Copy the code

However, in ES2015, the math.hypot method is provided to compute the square root of the parameter.

const v1 = [3, 4]; console.log(Math.hypot(... v1)); / / 5Copy the code

Currently, all browsers except Internet Explorer support this method.

👉🏻 Cold facts – Math.hypot pit: You might think math.hypot is a built-in function that should perform better than math.sqrt, but it doesn’t. Let’s write a test script:

function length(v) {
  const dimension = v.length;
  let ret = 0;
  for(let i = 0; i < dimension; i++) {
    ret += v[i] ** 2;
  }
  return Math.sqrt(ret);
}

Copy the code
// Math.hypot const v1 = Array(10).fill(0).map(() => Math.random()); const result = Math.hypot(... v1);Copy the code
//Math.sqrt
const v1 = Array(10).fill(0).map(() => Math.random());
const result = length(v1);

Copy the code

When tested with Jsperf, the results were surprising, with math.hypot being around 40% slower than Math.sqrt on my Chrome 75.

Maybe I’m using the wrong posture? But Kangax wrote many more cases to test it as early as 14:

As a result…

Therefore, a mathematical function supported by ES2015 is a very common operation, but not many people use it, and not many people introduce it, there is a reason — the performance is anxious.

But just because Hypot isn’t as good as SQRT doesn’t mean it’s completely unavailable.

In some cases, you can get results with hypot that you can’t get with SQRT. For very large numbers or very small numbers:

Math.hypot(2e200, 3e200); // 3.6055512754639894e+200 Math. SQRT (2e200 ** 2 + 3e200 ** 2); // Infinity Math.hypot(2e-200, 3e-200); // 3.6055512754639893E-200 Math. SQRT (2e-200 ** 2 + 3e-200 ** 2); / / 0Copy the code

So if we’re dealing with very large numbers or very small numbers, we can use Math.hypot, and in general, it’s better to use Math.sqrt. Such as:

const result = Math.sqrt(x ** 2 + y ** 2); if(! Number.isFinite(result)) result = Math.hypot(x, y);Copy the code

Any more questions about Math.hypot can be discussed in the issue.