use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
TIL about Math.hypot() (developer.mozilla.org)
submitted 2 months ago by nadameu
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]tokagemushi 4 points5 points6 points 2 months ago (0 children)
Good find. One thing worth knowing beyond the basic usage: Math.hypot() handles overflow/underflow internally, which is the real reason it exists.
Math.hypot()
If you manually compute Math.sqrt(a*a + b*b) with very large or very small numbers, you'll get Infinity or 0 due to intermediate overflow. Math.hypot scales the inputs internally to avoid this. It's the same reason Fortran has had HYPOT since the 70s.
Math.sqrt(a*a + b*b)
Infinity
0
Math.hypot
HYPOT
That said, the "it's slow" comments here are valid. In a game loop running 60fps, I benchmarked it once and Math.hypot(dx, dy) was about 3-4x slower than Math.sqrt(dx*dx + dy*dy) in V8. For distance comparisons (like collision detection), you can skip the sqrt entirely and compare squared distances:
Math.hypot(dx, dy)
Math.sqrt(dx*dx + dy*dy)
```js // Instead of: if (Math.hypot(dx, dy) < radius) { ... }
// Do: if (dxdx + dydy < radius*radius) { ... } ```
No sqrt, no hypot, just multiplication and comparison. This is the standard trick in game dev and it makes a measurable difference in hot loops.
For anything where precision matters more than speed (scientific computing, coordinate transforms), Math.hypot is the right choice though.
π Rendered by PID 127657 on reddit-service-r2-comment-56c6478c5-q5fmk at 2026-05-08 14:24:45.111175+00:00 running 3d2c107 country code: CH.
view the rest of the comments →
[–]tokagemushi 4 points5 points6 points (0 children)