w3resource

JavaScript: Volume of a Sphere

JavaScript Math: Exercise-63 with Solution

Volume of a Sphere

Write a JavaScript program to calculate the volume of a Sphere.

From Wikipedia -
A sphere is a geometrical object that is a three-dimensional analogue to a two-dimensional circle. A sphere is the set of points that are all at the same distance r from a given point in three-dimensional space.That given point is the centre of the sphere, and r is the sphere's radius. The earliest known mentions of spheres appear in the work of the ancient Greek mathematicians.

Sample Data:
JavaScript Math: Volume of a Sphere
JavaScript Math: Volume of a Sphere

Sample Solution:

JavaScript Code:

// Define a function volume_Sphere that calculates the volume of a sphere given its radius.
const volume_Sphere = (radius) => {
  // Check if the radius is a number and positive.
  is_Number(radius, 'Radius');
  // Return the volume of the sphere.
  return (4 / 3 * Math.PI * radius ** 3);
}

// Define a function is_Number that checks if a given value is a number and positive.
const is_Number = (n, n_name = 'number') => {
  // If the given value is not a number, throw a TypeError.
  if (typeof n !== 'number') {
    throw new TypeError('The ' + n_name + ' is not Number type!');
  } 
  // If the given value is negative or not a finite number, throw an Error.
  else if (n < 0 || (!Number.isFinite(n))) {
    throw new Error('The ' + n_name + ' must be a positive values!');
  }
}

// Call the volume_Sphere function with valid and invalid arguments and output the results.
console.log(volume_Sphere(4.0));
console.log(volume_Sphere('4.0'));
console.log(volume_Sphere(-4.0));

Output:

268.082573106329
----------------------------------------------------
Uncaught TypeError: The Radius is not Number type! 
 at https://cdpn.io/cpe/boomboom/pen.js?key=pen.js-19d5ed64-fc75-d66c-3f3c-fbac27f90859:7
---------------------------------------------------------------------------------------
Uncaught Error: The Radius must be a positive values! 
 at https://cdpn.io/cpe/boomboom/pen.js?key=pen.js-809901d5-f749-5312-6519-fd58b9f462c0:11

Flowchart:

JavaScript Math flowchart of Volume of a Sphere

Live Demo:

See the Pen javascript-math-exercise-63 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus.

Previous: Volume of a Pentagonal Prism.
Next: Volume of a Hemisphere

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-math-exercise-63.php