To calculate the square root of the number in JavaScript, you can use the function Math.sqrt()
. You pass in a number, and it returns the square root of this number.
console.log(Math.sqrt(4)); // 2
console.log(Math.sqrt(16)); // 4
console.log(Math.sqrt(64)); // 8
console.log(Math.sqrt(100)); // 10
Square root of zero is 0
.
console.log(Math.sqrt(0)); // 0
Square root of one is 1
.
console.log(Math.sqrt(1)); // 1
If you try to multiply the number by itself in JavaScript and take the square root, you’ll get the same number you’ve started with.
const x = 1234;
console.log(Math.sqrt(x * x)); // 1234
In JS, you can’t calculate the square root of negative numbers, thus Math.sqrt
returns NaN
.
console.log(Math.sqrt(-4)); // NaN
console.log(Math.sqrt(-1)); // NaN
Read more JavaScript tutorials or Learn Full-Stack JS from scratch!