Using the Math.sqrt()
method in JavaScript
Math.sqrt()
is a built-in function in JavaScript that returns the square root of a given number. The function takes one argument, which is the number to be square rooted.
The syntax for using Math.sqrt()
is as follows:
Math.sqrt(number)
where number
is the number you want to find the square root of.
For example, to find the square root of 25, you would write:
Math.sqrt(25) // returns 5
Note that the Math.sqrt()
function returns a NaN
(Not a Number) value if the argument passed to it is negative.
Example 1: Normal Square Root Calculation
To find the square root of 16 using math.sqrt()
method, you can use the following code:
let x = 16;
let result = Math.sqrt(x);
console.log(result);
Output
4
Example 2: Square Root of a Decimal Value
To find the square root of a decimal using Math.sqrt()
method, you can use the following code:
let num = 2.25;
let squareRoot = Math.sqrt(num);
console.log(squareRoot);
Output
1.5
Example 3: Calculating the distance between two points in a 2D plane
To calculate the distance between two points (x1, y1) and (x2, y2) in a 2D plane, you can use the following formula:
let x1 = 1;
let y1 = 2;
let x2 = 4;
let y2 = 6;
let distance = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
console.log(distance);
Output
5
Here, we are using the Math.sqrt()
method to calculate the square root of the sum of the squares of the differences between the x and y coordinates of the two points.
Example 4: Calculating the standard deviation of an array of numbers
To calculate the standard deviation of an array of numbers, you can use the following formula:
let numbers = [2, 4, 6, 8, 10];
let sum = numbers.reduce((acc, val) => acc + val, 0);
let mean = sum / numbers.length;
let variance =
numbers.reduce((acc, val) => acc + (val - mean) ** 2, 0) /
(numbers.length - 1);
let stdDev = Math.sqrt(variance);
console.log(stdDev);
Output
3.1622776601683795
Here, we are using the Math.sqrt()
method to calculate the square root of the variance of the array of numbers.
Summary
The Math.sqrt()
method is a built-in method in JavaScript that is used to calculate the square root of a number, and is part of the Math
object in JavaScript. With the Math.sqrt()
method, we can carry out a ton of mathematical operations involve square roots from standard deviation to distance between two points.
References
Math.sqrt() - JavaScript | MDN (mozilla.org)