Computer >> Computer tutorials >  >> Programming >> Javascript

Calculating the area of a triangle using its three sides in JavaScript


Problem

We are required to write a JavaScript function that takes in the three sides of a triangle and uses Heron’s formula to calculate its area.

Example

Following is the code −

const s1 = 10;
const s2 = 8;
const s3 = 7;
const findArea = (s1, s2, s3) => {
   const arr = [];
   const arguments = [s1, s2, s3];
   for(let i = 0; i < arguments.length; i++){
      arr.push(arguments[i]);
   };
   let s = (arr[0] + arr[1] + arr[2]) / 2;
   return Math.sqrt(s * (s - arr[0]) * (s - arr[1]) * (s - arr[2]));
};
console.log(findArea(s1, s2, s3));

Output

27.810744326608734