
Discovered something interesting while solving a collision detection related JS problem, most of the time its usual to find distance between two points with this approach
const dx = x2 - x1;
const dy = y2 - y1;
const distance = Math.sqrt(dx * dx + dy * dy)
// An interesting way to achieve this in JS with much readable and efficient way is
const distance = Math.hypot(x2-x1 , y2 - y1);
// also 3d distances
const distance3d = Math.hypot(x2-x1, y2 - y1, z2 - z1);
Why use Math.hypot ?
✔ Cleaner & more readable
✔ Handles more than 2D (supports n-dimensions)
✔ Avoids overflow/underflow issues: It internally optimizes calculations to prevent floating-point precision errors. Although these will be pretty rare in day-to-day coding flows
Should You Use Math.hypot?
If you care about readability and correctness, yes!
If you're working on performance-sensitive code (games, physics, etc.), manually squaring values can be faster.
But most regular devs don't even know it exists—so using it might make you look like a wizard. ♂️