Looking for calculating JavaScript square root? In this quick tutorial, you will learn how to find the square root of a number in JavaScript.

In, the previous JavaScript tutorial we used the inbuilt method pow() in Math class to find the square of a number.

Using Math.sqrt() Method to Find Square Root

The Math.sqrt() method accepts a single argument of type number.



Where x is a positive number for which you want to find the square root.

JavaScript Program to Find the Square Root

For example, here are a few JS programs to find the square root.

Example 1: JavaScript square root of a positive number.

let val = 49;
console.log(Math.sqrt(val)); // 7

Example 2: JavaScript square root of a floating-point number?

let val = 5.14;
console.log(Math.sqrt(val)); // 2.226...

Example 3: What if we pass a negative number to sqrt() method?

let val = -9;
console.log(Math.sqrt(val)); // NaN

As a result, If a negative number is passed NaN is returned.

Example 4: What if a number is passed as a string to Math.sqrt() method?

let val = '36';
console.log(Math.sqrt(val)); // 6

Isn’t it strange? We passed a number as a string, then also the sqrt() method returns its square root. Check for yourself.

Example 5: What if a word is passed as a string?

let val = 'two';
console.log(Math.sqrt(val)); // NaN

Similarly, if a string containing alphabets is passed then NaN is returned.

Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed.