how to calculate area of a sphere in javascript

To calculate the area of a sphere in JavaScript, we first need to know its radius. Once we have the radius, we can use the formula:

Area = 4 * π * r^2

where π is a mathematical constant approximately equal to 3.14159 and r is the radius of the sphere.

Here's the code to calculate the area of a sphere in JavaScript:

index.tsx
// function to calculate the area of a sphere
function calculateSphereArea(radius) {
  const PI = Math.PI;
  const area = 4 * PI * Math.pow(radius, 2);
  return area;
}

// example usage
const radius = 5;
const area = calculateSphereArea(radius);
console.log(`The area of a sphere with radius ${radius} is ${area}`);
317 chars
12 lines

In this code, we define a function calculateSphereArea which takes the radius of the sphere as input and returns its area. We define the constant PI using the Math.PI property, and then use the formula to calculate the area.

To test our function, we define a radius of 5 and call the calculateSphereArea function with this value. Finally, we log the result to the console using a template string.

gistlibby LogSnag