JS Example for Beginners: JavaScript Program to Find the Square Root

(JavaScript programming Example for Beginners)

JavaScript Program to Find the Square Root

In this example, you’ll learn to write a program to find the square root of a number in JavaScript.


To find the square root of a number in JavaScript, you can use the built-in Math.sqrt() method. Its syntax is:

Math.sqrt(number);

Here, the Math.sqrt() method takes a number and returns its square root.

 


Example: Square Root of a Number


// take the input from the user
let number = prompt('Enter the number: ');

let result = Math.sqrt(number);
console.log(`The square root of ${number} is ${result}`);

Output

Enter the number: 9 
The square root of 9 is 3

Example 2: Square Root of Different Data Types


let number1 = 2.25;
let number2 = -4;
let number3 = 'hello';

let result1 = Math.sqrt(number1);
let result2 = Math.sqrt(number2);
let result3 = Math.sqrt(number3);

console.log(`The square root of ${number1} is ${result1}`);
console.log(`The square root of ${number2} is ${result2}`);
console.log(`The square root of ${number3} is ${result3}`);

Output

The square root of 2.25 is 1.5
The square root of -4 is NaN
The square root of hello is NaN
  • If a 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.

 

 

JS Example for Beginners: JavaScript Program to Find the Square Root

Sign up to get end-to-end “Learn By Coding” example.



Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.