Emmanuel Akinfulubi

JavaScriptMath

Math.hypot and vector length in JavaScript

Intermediate · 4 min read

How far is the point (3, 4) from the corner of a graph at (0, 0)? Walk 3 across and 4 up, and the straight-line distance is 5. That distance is called the length of the vector (3, 4). Games use it to move characters at a steady speed, maps use it for "as the crow flies" distances, and drawing apps use it to measure a drag.

In this tutorial you will find vector lengths in two ways: by hand with Math.sqrt, and with Math.hypot. Then you will find a pair of numbers where the hand-made version breaks and returns Infinity, while Math.hypot gets the right answer. You need to know Math.sqrt and how to write an arrow function.

Pythagoras in one line

For a right-angled triangle, the long side squared equals the sum of the other two sides squared. So the length of (a, b) is the square root of a * a + b * b:

JavaScript

console.log(Math.sqrt(3 * 3 + 4 * 4)); // 5

The same idea works in 3D: for (a, b, c), add all three squares before taking the root.

A vector, in plain words

A vector here is just a list of numbers that describes a movement: so far across, so far up, and in 3D, so far forward. Its length is how far the movement goes in a straight line.

Here is the exercise. Try it yourself first if you like, then read on and we will build it together.

30 Math.hypot, and why not to square first

fair

Find the length of the vector (3, 4) and of (2, 3, 6). Then find a pair of inputs where Math.sqrt(a * a + b * b) gives Infinity and Math.hypot does not.

Stuck? Three hints, smallest first
  1. 1. Math.hypot takes any number of arguments and returns the square root of the sum of their squares.
  2. 2. Squaring 3e200 overflows a double, even though the answer would fit comfortably.
  3. 3. hypot scales its inputs internally before squaring, which is exactly what that buys you.

Step 1: the hand-made version

Step 1

const manual = (a, b) => Math.sqrt(a * a + b * b);
console.log(manual(3, 4)); // 5

That is the classic 3-4-5 triangle, and the formula gets it right.

Step 2: Math.hypot

Math.hypot takes any number of values and returns the square root of the sum of their squares. The name comes from "hypotenuse", the long side of a right-angled triangle.

Step 2

console.log(Math.hypot(3, 4));    // 5
console.log(Math.hypot(2, 3, 6)); // 7

The second line is a 3D length: 4 + 9 + 36 is 49, and the root of 49 is 7. You don't have to write a separate function for 2D and 3D.

Step 3: a very big vector

Now try huge numbers. 3e200 means 3 times 10 to the 200th, written in scientific notation. The largest JavaScript number is about 1.8e308. Square 3e200 and you get 9e400, which is far too big:

Step 3

console.log(3e200 * 3e200);          // Infinity
console.log(manual(3e200, 4e200));   // Infinity

The real answer is 5e200, which fits easily. Only the middle step, the squaring, was too big. When a calculation goes past the largest number like this, it is called overflow, and JavaScript turns the value into Infinity without any error.

Step 4: hypot survives

Step 4

console.log(Math.hypot(3e200, 4e200)); // 4.9999999999999995e+200

That is 5e200, give or take a rounding in the last digit. The difference is about one part in ten million billion. You can check it is that close:

JavaScript

const h = Math.hypot(3e200, 4e200);
console.log(Math.abs(h / 5e200 - 1) < 1e-15); // true

How does hypot avoid the overflow? It scales the values down before squaring them, so the middle step stays small, and scales the result back up at the end. That is the whole reason it exists: it isn't just a shorter way to write the formula.

Step 5: the edge cases

Step 5

console.log(Math.hypot());              // 0
console.log(Math.hypot(Infinity, NaN)); // Infinity

With no values, the sum of squares is 0, so the length is 0. The second line is a rule written into JavaScript: if any value is infinite, the answer is Infinity, even when another value is NaN.

When to use which

Math.hypot is the safe choice and handles any size of number. It is also slower than the hand-made formula. In a tight loop over screen pixels, where values are small and speed matters, Math.sqrt(a * a + b * b) is a reasonable choice.

The full solution

The answer panel defines manual, then compares it with Math.hypot on the 3-4-5 triangle, the 3D vector, the huge pair and the edge cases. The checks underneath confirm that the manual version returns Infinity for 3e200 and 4e200 while hypot lands within a rounding of 5e200. Press Run to see the output.

The answer

const manual = (a, b) => Math.sqrt(a * a + b * b);

console.log('hypot(3, 4)      :', Math.hypot(3, 4));
console.log('hypot(2, 3, 6)   :', Math.hypot(2, 3, 6));
console.log('manual(3, 4)     :', manual(3, 4));
console.log('3e200 squared    :', 3e200 * 3e200, '<- overflowed');
console.log('manual(3e200, 4e200):', manual(3e200, 4e200));
console.log('hypot(3e200,4e200)  :', Math.hypot(3e200, 4e200), '<- should be 5e200');
console.log('hypot()          :', Math.hypot());
console.log('with an Infinity :', Math.hypot(Infinity, NaN));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the 3-4-5 triangle', Math.hypot(3, 4), 5);
test('it takes any number of arguments', Math.hypot(2, 3, 6), 7);
test('the manual version agrees at ordinary magnitudes', manual(3, 4), 5);
test('but squaring 3e200 overflows a double', 3e200 * 3e200 === Infinity, true);
test('so the manual version returns Infinity', manual(3e200, 4e200) === Infinity, true);
test('while hypot survives, to within a rounding', Math.hypot(3e200, 4e200), 4.9999999999999995e+200);
test('which is 5e200 to fifteen digits', Math.abs(Math.hypot(3e200, 4e200) / 5e200 - 1) < 1e-15, true);
test('hypot of no arguments is 0', Math.hypot(), 0);
test('and an Infinity wins even against a NaN', Math.hypot(Infinity, NaN) === Infinity, true);

Math.hypot is not sugar. It divides by the largest magnitude first, squares the scaled values, then multiplies back — so intermediate overflow and underflow are avoided for inputs the answer could never have overflowed on. The 3e200 pair is the demonstration: the true answer 5e200 is well inside range, and only the naive intermediate a * a was not.

Two footnotes. hypot is slower than the manual form, so in a tight inner loop over screen coordinates the manual version is the right call. And the last assertion follows the specification: an infinite argument dominates, even when another argument is NaN.

Common mistakes

  • Squaring huge numbers by hand. The middle step can overflow even when the answer fits. Use Math.hypot.
  • Writing a separate function for 3D. Math.hypot(a, b, c) already takes any number of values.
  • Comparing the result with ===. Math.hypot(3e200, 4e200) isn't exactly 5e200. Compare within a small tolerance.

Try it yourself

  1. Find the distance between the points (1, 2) and (4, 6) with Math.hypot(4 - 1, 6 - 2).
  2. Write normalize(x, y) that divides both parts by the length, so the new vector has length 1. Test it on (3, 4).
  3. Find a pair of tiny numbers, like 1e-200, where the manual formula returns 0 but Math.hypot doesn't.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.