Math.sqrt

Category:Math

Takes the square root of x.

There are some math calculations that require you to take the square root. Math.sqrt(x) does not change the value of x, rather it returns the the square root of x or in other words the result of taking x the power of (1/2).

Examples

var t = Math.sqrt(16);
console.log(t);

Pythagorean Theorem

Input the lengths of sides a and b and hit "Calculate" to find the the hypotenuse of that right triangle. This example also uses Math.pow and Math.round to display results.

                            
//Using the Math.sqrt block to help us calculate the length of a right triangle's hypotenuse using the Pythagorean Theorem
textLabel("title", "What's the hypotenuse(side c)?");
image("pic", "https://upload.wikimedia.org/wikipedia/commons/thumb/0/09/Pythagorean_theorem_abc.svg/123px-Pythagorean_theorem_abc.svg.png");
textLabel("questionA", "What's the length of side a?");
textInput("aInput", "");
textLabel("questionB", "What's the length of side b?");
textInput("bInput", "");
button("calculate", "Calculate");
textLabel("answer", "");
onEvent("calculate", "click", function( ) {
  var sideA = getNumber("aInput");
  var sideB = getNumber("bInput");
  var cSquared = Math.pow(sideA, 2) + Math.pow(sideB, 2);
  var sideC = Math.sqrt(cSquared);
  setText("answer", "Side c = " + Math.round(sideC));
});

                        

Syntax

Math.sqrt(x);

Parameters

NameTypeRequired?Description
x Number A number to take the square root of

Returns

A number that is the square root of x

Found a bug in the documentation? Let us know at documentation@code.org