w3resource

JavaScript: Volume of a Triangular Prism

JavaScript Math: Exercise-61 with Solution

Write a JavaScript program to calculate the volume of a Triangular Prism.

From Wikipedia -
In geometry, a triangular prism is a three-sided prism; it is a polyhedron made of a triangular base, a translated copy, and 3 faces joining corresponding sides. A right triangular prism has rectangular sides, otherwise it is oblique. A uniform triangular prism is a right triangular prism with equilateral bases, and square sides.

Sample Data:
JavaScript Math: Volume of a Triangular Prism
JavaScript Math: Volume of a Cylinder

Sample Solution:

JavaScript Code:

// Define a function volume_Triangular_Prism that calculates the volume of a triangular prism given its base sides and height.
const volume_Triangular_Prism = (a, b, c, h) => {
  // Check if the base sides and height are numbers and positive.
  is_Number(a, 'BaseSide_a');
  is_Number(b, 'BaseSide_b');
  is_Number(c, 'BaseSide_c');
  is_Number(h, 'Height');
  // Return the volume of the triangular prism.
  return (1/4 * h * Math.sqrt(-(a**4) + 2*a*a*b*b + 2*a*a*c*c - (b**4) + 2*b*b*c*c - (c**4)));
}

// 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_Triangular_Prism function with valid and invalid arguments and output the results.
console.log(volume_Triangular_Prism(2.0, 4.0, 4.0, 7.0));
console.log(volume_Triangular_Prism('2.0', 4.0, 4.0, 7.0));

Output:

27.11088342345192
-----------------------------------------------------------
Uncaught TypeError: The BaseSide_a is not Number type! 
 at https://cdpn.io/cpe/boomboom/pen.js?key=pen.js-d5ecc06d-a003-d50c-3d8f-00a52b5e6f98:10

Flowchart:

JavaScript Math flowchart of Volume of a Triangular Prism

Live Demo:

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


Improve this sample solution and post your code through Disqus.

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.