Signup/Sign In
PUBLISHED ON: DECEMBER 26, 2022

JavaScript program to find the Square Root of a Number

Finding the square root of a number is a common operation in mathematics that is used to determine the length of the diagonal of a square with sides of a given length. In JavaScript, the Math.sqrt() function can be used to find the square root of a number. In this tutorial, we will learn how to use this function to find the square root of a number in JavaScript. We will also discuss how to handle errors that may occur when using this function. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and know more from here.

The Math.sqrt() method in JavaScript is used to find the square root of the number passed as a parameter to the function defined by the user.

Syntax

Math.sqrt(number)

The Math.sqrt() method returns the square root of a number.

Parameter

number - it takes any variable which is a number whose square root needs to be found out as a result.

Return

  • If 0 or a positive number is passed in the Math.sqrt() method, then the square root of that number is returned.
  • If a negative number is passed, NaN is returned.
  • If a string is passed, NaN is returned.

JavaScript program to find the Square Root of a Number

// Write a code to find the square root of a number

var num1 = 16;
var sq1 = Math.sqrt(num1);
var num2 = 2.25;
var sq2 = Math.sqrt(num2);
var num3 = -4;
var sq3 = Math.sqrt(num3);
var num4 = 'hello';
var sq4 = Math.sqrt(num4);
console.log("The Square Root of the given number is :" , sq1);
console.log("The Square Root of the given number is :" , sq2);
console.log("The Square Root of the given number is :" , sq3);
console.log("The Square Root of the given number is :" , sq4);


The Square Root of the given number is : 4
The Square Root of the given number is : 1.5
The Square Root of the given number is : NaN
The Square Root of the given number is : NaN

Conclusion

In conclusion, we have learned how to calculate the square root of a number in JavaScript. We explored various methods for finding the square root, including using the Math.sqrt() function. Overall, calculating the square root of a number is a fundamental operation that is useful in many contexts, and being able to do so in JavaScript can be a valuable skill for any developer.

We hope that this tutorial has provided you with a solid understanding of how to find the square root of a number in JavaScript, and that you are now able to incorporate this functionality into your own programs and projects.

Take the first step towards becoming a JavaScript pro by signing up for our Interactive Course now!



About the author:
Proficient in the creation of websites. Expertise in Java script and C#. Discussing the latest developments in these areas and providing tutorials on how to use them.