Math.hypot() -> Small convenience for finding euclidean distance

Math.hypot() -> Small convenience for finding euclidean distance

posted Originally published at www.linkedin.com 1 min read

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. ♂️

0 votes
0 votes

More Posts

Modern React Patterns for Financial Dashboards

Pocket Portfolio - Nov 11

I Asked AI for Help — Now It Runs My Life

Yash - Oct 17

A module for a hexagonal masonry layout with CSS and JavaScript

Ingo Steinke - Oct 1

How to Integrate LinkedIn API in a Web App for Login and User Details

Sunny - Sep 30

Scaffolder-Toolkit (dk): Your Universal CLI for Professional Development

Waffeu Rayn - Sep 17
chevron_left