Finding area of triangle in JavaScript using Heron’s formula


We are given the lengths of three sides of a triangle and we are required to write a function that returns the area of the triangle using the length of its sides.

Heron's formula

We can calculate the area of a triangle if we know the lengths of all three sides, using Heron's formula −

Step 1 − Calculate "s" (half of the triangles perimeter) −

s = (a+b+c) / 2

Step 2 − Then calculate the Area using Herons formula −

A = sqrt( s(s-a)(s-b)(s-c) )

Example

So, Let’s write the code for this function −

const sides = [12, 4, 9];
const areaOfTriangle = sides => {
   const [a, b, c] = sides;
   const sp = (a + b + c) / 2;
   const aDifference = sp - a;
   const bDiffernece = sp - b;
   const cDifference = sp - c;
   const area = Math.sqrt(sp * aDifference * bDiffernece * cDifference);
   return area;
};
console.log(areaOfTriangle(sides));

Output

The output in the console: −

13.635890143294644

Updated on: 15-Sep-2020

601 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements