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
-
Economics & Finance
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 triangle's perimeter):
s = (a + b + c) / 2
Step 2 ? Then calculate the Area using Heron's formula:
A = ?(s(s-a)(s-b)(s-c))
Syntax
function heronFormula(a, b, c) {
const s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
Example
Let's implement the Heron's formula to find the area of a triangle with sides 12, 4, and 9:
const sides = [12, 4, 9];
const areaOfTriangle = sides => {
const [a, b, c] = sides;
const s = (a + b + c) / 2;
const area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
return area;
};
console.log("Triangle sides:", sides);
console.log("Area:", areaOfTriangle(sides));
Triangle sides: [ 12, 4, 9 ] Area: 13.635890143294644
Alternative Implementation
Here's a more traditional function approach with input validation:
function calculateTriangleArea(a, b, c) {
// Check if triangle is valid
if (a + b <= c || a + c <= b || b + c <= a) {
return "Invalid triangle: sides don't satisfy triangle inequality";
}
const s = (a + b + c) / 2;
const area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
return parseFloat(area.toFixed(2));
}
// Valid triangle
console.log("Triangle (5, 4, 3):", calculateTriangleArea(5, 4, 3));
// Invalid triangle
console.log("Triangle (1, 1, 5):", calculateTriangleArea(1, 1, 5));
Triangle (5, 4, 3): 6 Triangle (1, 1, 5): Invalid triangle: sides don't satisfy triangle inequality
Key Points
- Heron's formula works for any triangle when all three side lengths are known
- The semi-perimeter (s) is half the sum of all three sides
- Always validate that the sides form a valid triangle using triangle inequality theorem
- Use
Math.sqrt()to calculate the square root in JavaScript
Conclusion
Heron's formula provides an efficient way to calculate triangle area using only side lengths. Remember to validate inputs to ensure the sides form a valid triangle before applying the formula.
