You can find the square root of a number in JavaScript using the Math.sqrt() function. Here's a simple example:
// Function to find the square root of a number
function findSquareRoot(number) {
// Check if the number is non-negative
if (number >= 0) {
// Use Math.sqrt() to calculate the square root
return Math.sqrt(number);
} else {
// If the number is negative, return NaN (Not a Number)
return NaN;
}
}
// Example usage
let numToFindSquareRoot = 25;
let result = findSquareRoot(numToFindSquareRoot);
if (!isNaN(result)) {
console.log(`The square root of ${numToFindSquareRoot} is: ${result}`);
} else {
console.log(`Cannot calculate the square root of a negative number.`);
}
In this example, the findSquareRoot function takes a number as an argument, checks if it's non-negative, and then uses
Math.sqrt() to calculate the square root. If the number is negative, it returns
NaN (Not a Number).
You can change the value of numToFindSquareRoot to find the square root of different numbers. Note that the result will be a floating-point number, even if the input is an integer.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
You can find the square root of a number in JavaScript using the Math.sqrt() function. Here's a simple example:
In this example, the findSquareRoot function takes a number as an argument, checks if it's non-negative, and then uses Math.sqrt() to calculate the square root. If the number is negative, it returns NaN (Not a Number).
You can change the value of numToFindSquareRoot to find the square root of different numbers. Note that the result will be a floating-point number, even if the input is an integer.