Golfed only, -23 bytes
ES6 supports default parameters.
Default function parameters allow formal parameters to be initialized
with default values if no value or
undefined is passed.
So, we can replace
y=y||x with just
(y*y-x)/(2*y) can be rewritten as
y/2-x/2/y. And since this expression appears twice in the code, we can assign it to a new variable z.
As suggested by ETHproductions in the comments, we now can save 2 more bytes by multiplying z by 2:
Alternate version, -26 bytes
To save more bytes, another approach is to just iterate enough times rather than using a test on the result.
That could be done that way:
We start with
k = x and divide it by 2 at each iteration. No matter the initial value of x, we will eventually reach 0 because of arithmetic underflow.
The good thing about this method is that the number of iterations doesn't heavily rely on the value of x. For instance, we'll get 1142 iterations for x = 1020 and 1009 iterations for x = 10 -20. In both cases, we iterate far too many times than necessary, without exceeding the default maximum number of iterations of common browsers.
Some more notes:
- The error is negligible for x > 10 -215 and quickly grows below this bound.
- For the same byte count and less iterations, we can divide by 9 instead. In that case, a safe bound is x > 10 -124.
Math.sqrt(), this method does not return
NaN for negative numbers or
±Infinity (and neither does the original code).