Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
Advertisements
