In this example, you will learn to write a program to find square root in javascript.
But before going into the example, you must have knowledge of the following JavaScript topics:
To find the square root of a number in javascript, we can use the Math.sqrt()
method of javascript. Its syntax is:
Math.sqrt(number);
Here, Math.sqrt()
takes in the number and returns its square root.
Example 1: Find the Square Root of a Number
let num = 4;
// finding the square root
let root = Math.sqrt(num);
console.log(`Square root of ${num} is: ${root}`);
Output
Square root of 4 is: 2
Example 2: Find the Square Root of the User Input Number
// user input number
let num = prompt('Enter the number: ');
// finding square root
let root = Math.sqrt(num);
console.log(`Square root of ${num} is: ${root}`);
Output
Enter the number: 4
Square root of 4 is: 2
Example 3: Square Root of Different Data Types
let num1 = 4.8;
let num2 = 'Hello';
let num3 = '-4';
// finding square root
let root1 = Math.sqrt(num1);
let root2 = Math.sqrt(num2);
let root3 = Math.sqrt(num3);
console.log(`Square root of ${num1} is: ${root1}`);
console.log(`Square root of ${num2} is: ${root2}`);
console.log(`Square root of ${num3} is: ${root3}`);
Output
Square root of 4.8 is: 2.1908902300206643
Square root of Hello is: NaN
Square root of -4 is: NaN
If 0 or a positive value is passed, Math.sqrt()
method will return the square root of that value
If a string is passed, NaN
is returned
If a negative value is passed, NaN
is returned.