Square root and cube root in JavaScript
Beginner · 4 min read
A square root answers the question "what number, multiplied by itself, gives this?" The square root of 144 is 12, because 12 times 12 is 144. A cube root does the same with three copies: the cube root of 27 is 3, because 3 times 3 times 3 is 27.
You meet square roots whenever you measure a distance on a screen or a map, work out a standard deviation, or size a square from its area. In this tutorial you will use Math.sqrt and Math.cbrt, see what they do with negative numbers, and find out why squaring the square root of 2 doesn't quite give back 2. You only need to know how to call a function and print the result.
Two functions, two jobs
Math.sqrt(x)gives the square root.Math.cbrt(x)gives the cube root.
Some square roots come out exact, like 12. Others never end. The square root of 2 is 1.41421356... and the digits go on forever without repeating. A number like that is called irrational. A computer can only store a fixed number of digits, so it keeps the closest value it can.
Here is the exercise. Try it yourself first if you like, then read on and we will build it together.
28 Square roots and cube roots
easyTake the square root of 144 and of 2, and the cube root of -27. Then show that squaring Math.sqrt(2) does not give back 2.
Stuck? Three hints, smallest first
- 1.
Math.sqrtfor squares,Math.cbrtfor cubes. - 2.
Math.sqrtof a negative isNaN;Math.cbrtof a negative is fine. - 3. An irrational root cannot be stored exactly, so the round trip lands a hair off.
Step 1: a perfect square
console.log(Math.sqrt(144)); // 12
144 is a perfect square: a whole number times itself. Its root is exact.
Step 2: an irrational root
console.log(Math.sqrt(2)); // 1.4142135623730951
That is the closest value a JavaScript number can hold to the true square root of 2. It is very close, but it isn't exact.
Step 3: the round trip
If the root were exact, squaring it would give back 2. Try it:
console.log(Math.sqrt(2) ** 2); // 2.0000000000000004
console.log(Math.sqrt(2) ** 2 === 2); // false
The result is a tiny bit over 2. The error is in the very last digit the number can store, but === compares every digit, so the check fails.
The lesson: never test "is n a perfect square?" by writing Math.sqrt(n) ** 2 === n. Rounding can make it lie. A later exercise shows a safe way that works with whole numbers.
Step 4: negative numbers
No ordinary number times itself gives a negative result, since two negatives multiply to a positive. So Math.sqrt of a negative number returns NaN, "Not a Number":
console.log(Math.sqrt(-4)); // NaN
It doesn't throw an error, so the NaN can travel on through your code. If a negative is possible, check before taking the root.
Cube roots are different. -3 times -3 times -3 is -27, so negative numbers have real cube roots, and Math.cbrt returns them:
console.log(Math.cbrt(-27)); // -3
Step 5: the power 0.5
Raising to the power one half is the same as taking a square root:
console.log(144 ** 0.5); // 12
Both are fine. Math.sqrt says what you mean more clearly, so most code uses it.
Step 6: the edges
Two edge values behave the way you would hope:
console.log(Math.sqrt(0)); // 0
console.log(Math.sqrt(Infinity)); // Infinity
Step 7: distance with Math.hypot
The most common use of a square root is distance. For a right-angled triangle with sides 9 and 12, the long side is the square root of 9 squared plus 12 squared. Math.hypot does all of that in one call:
console.log(Math.sqrt(9 * 9 + 12 * 12)); // 15
console.log(Math.hypot(9, 12)); // 15
The name comes from "hypotenuse", the long side of a right-angled triangle.
The full solution
The answer panel prints the root of 144, the root of 2 and its square, the negative cases, the power 0.5 version and the edges. The checks underneath confirm each value, including that the square of Math.sqrt(2) is 2.0000000000000004, and that Math.hypot(9, 12) is 15. Press Run to see the output.
console.log('sqrt(144) :', Math.sqrt(144));
console.log('sqrt(2) :', Math.sqrt(2));
console.log('squared again :', Math.sqrt(2) ** 2, '<- not 2');
console.log('sqrt(-4) :', Math.sqrt(-4));
console.log('cbrt(-27) :', Math.cbrt(-27));
console.log('144 ** 0.5 :', 144 ** 0.5);
console.log('sqrt(0), sqrt(Infinity):', Math.sqrt(0), Math.sqrt(Infinity));
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.
test('the root of a perfect square is exact', Math.sqrt(144), 12);
test('the root of 2 is irrational, so it is approximate', Math.sqrt(2), 1.4142135623730951);
test('squaring it does not return 2', Math.sqrt(2) ** 2 === 2, false);
test('it lands a hair over', Math.sqrt(2) ** 2, 2.0000000000000004);
test('the root of a negative is NaN', Number.isNaN(Math.sqrt(-4)), true);
test('but a cube root handles a negative', Math.cbrt(-27), -3);
test('sqrt of 0 is 0, and of Infinity is Infinity', [Math.sqrt(0), Math.sqrt(Infinity) === Infinity], [0, true]);
test('raising to the power 0.5 is the same function', 144 ** 0.5, 12);
test('and Math.hypot is sqrt of a sum of squares', Math.hypot(9, 12), 15);
Math.sqrt(2) ** 2 is the round-trip test worth internalising: irrational roots are stored to 53 bits, so squaring recovers a value one bit away from the original. Never write Math.sqrt(n) ** 2 === n; for a perfect-square test, work in integers as exercise 47 does.
Math.sqrt(-4) gives NaN rather than throwing, which is why a quadratic solver has to check its discriminant before rooting it — exercise 112 does exactly that.
Common mistakes
- Checking a root with
===after squaring.Math.sqrt(2) ** 2is not 2. Compare whole numbers, or allow a small tolerance. - Taking the square root of a negative. You get
NaN, not an error. Check the sign first. - Using
Math.sqrtfor a cube root of a negative.Math.cbrt(-27)is -3, and that is the function to use.
Try it yourself
- A square garden has an area of 50 square meters. Find the length of one side, rounded to 2 decimal places.
- Find the cube root of 1000 with
Math.cbrtand with1000 ** (1 / 3). Are they the same? - Write
safeSqrt(x)that returnsnullfor a negativexand the root otherwise.