Find the area of a triangle from three sides in JavaScript
Beginner · 4 min read
At school you learned that a triangle's area is half the base times the height. That works when you know the height. Often you don't: a surveyor measuring a plot of land, or a game working out the size of a shape, may only know the lengths of the three sides. In this tutorial you will find the area from the three sides alone.
You will write a function called triangleArea(a, b, c) and use it on a triangle with sides 5, 6 and 7. You need to know what a function is and how to do basic arithmetic in JavaScript. The formula and the checks are explained below.
Heron's formula
Almost two thousand years ago, Heron of Alexandria wrote down a way to get the area from the sides. It has two steps.
First, find half the perimeter. The perimeter is all three sides added together, and half of it is usually called s:
s = (a + b + c) / 2
Then the area is the square root of four numbers multiplied together:
area = √( s × (s − a) × (s − b) × (s − c) )
In JavaScript the square root is Math.sqrt().
Not every three numbers make a triangle
Try to build a triangle from sticks 1, 2 and 10 long. The two short sticks can't reach each other across the long one. The rule is called the triangle inequality: any two sides added together must be longer than the third.
If the two short sides add up to exactly the long one (1, 2 and 3), the "triangle" lies flat as a line and has no area at all. We treat that as not a triangle either.
Here is the exercise. Try it on your own first if you like, or build it with the steps below.
4 Area of a triangle from three sides
easyFind the area of a triangle whose sides are 5, 6 and 7.
Stuck? Three hints, smallest first
- 1. You have no height, so use Heron’s formula.
- 2. Half the perimeter is
s = (a + b + c) / 2, then the area isMath.sqrt(s * (s-a) * (s-b) * (s-c)). - 3. Not every three numbers make a triangle. Check that each pair sums to more than the third.
Step 1: half the perimeter
Start with s. For sides 5, 6 and 7 the perimeter is 18, so s is 9.
const a = 5, b = 6, c = 7;
const s = (a + b + c) / 2;
console.log(s); // 9
The brackets matter. Without them, JavaScript divides only c by 2 first, because division happens before addition.
Step 2: apply the formula
Now multiply the four numbers and take the square root.
function triangleArea(a, b, c) {
const s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
console.log(triangleArea(5, 6, 7)); // 14.696938456699069
console.log(triangleArea(3, 4, 5)); // 6
The 3, 4, 5 triangle has a right angle, so you can check it by hand: half of 3 times 4 is 6. When a new formula agrees with one you already trust, that is a good sign.
Step 3: see what goes wrong
Give the Step 2 function sides that can't form a triangle:
console.log(triangleArea(1, 2, 10)); // NaN
NaN means "Not a Number". Here s is 6.5, and s - c is negative, so the square root has no real answer. The trouble with NaN is that it spreads quietly: anything you add to it or multiply it by is also NaN, and nothing tells you where it came from.
Step 4: refuse impossible triangles
Check the triangle rule before doing any maths. If it fails, throw an error that says what was wrong. RangeError is the built-in error type for "this value is outside what I accept".
function triangleArea(a, b, c) {
if (a + b <= c || b + c <= a || a + c <= b) {
throw new RangeError(`no triangle has sides ${a}, ${b}, ${c}`);
}
const s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
|| means "or", so if any one pair is too short, the error is thrown. Using <= and not < is what also rejects the flat 1, 2, 3 case.
To see the message, catch the error with try and catch:
try {
triangleArea(1, 2, 10);
} catch (err) {
console.log(err.message); // no triangle has sides 1, 2, 10
}
Step 5: round for display
The exact area of the 5, 6, 7 triangle has a long tail of digits. toFixed(4) rounds it to four decimal places for showing to a person. It returns text, not a number.
console.log(triangleArea(5, 6, 7).toFixed(4)); // 14.6969
The full solution
The complete answer prints the 5, 6, 7 area exactly and rounded, checks the 3, 4, 5 triangle, and shows the error message for 1, 2, 10. Press Run to see the output.
function triangleArea(a, b, c) {
// Any two sides must together exceed the third, or there is no triangle.
if (a + b <= c || b + c <= a || a + c <= b) {
throw new RangeError(`no triangle has sides ${a}, ${b}, ${c}`);
}
const s = (a + b + c) / 2; // half the perimeter
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
const area = triangleArea(5, 6, 7);
console.log('sides 5, 6, 7 ->', area);
console.log('rounded ->', area.toFixed(4));
// A right triangle, where the answer is easy to check by hand: 3*4/2 = 6.
console.log('sides 3, 4, 5 ->', triangleArea(3, 4, 5));
let refused = '';
try { triangleArea(1, 2, 10); } catch (err) { refused = err.message; }
console.log('refused:', refused);
Output
5 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 5 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the asked-for triangle', Number(area.toFixed(4)), 14.6969);
test('a right triangle checks out by hand', triangleArea(3, 4, 5), 6);
test('an equilateral one', Number(triangleArea(2, 2, 2).toFixed(4)), 1.7321);
test('an impossible one is refused', refused.includes('no triangle'), true);
test('a degenerate flat one is refused too', (() => { try { triangleArea(1, 2, 3); return false; } catch { return true; } })(), true);
The validation is the part the original skips, and it matters: without it triangleArea(1, 2, 10) returns NaN, which then spreads silently through any arithmetic downstream. Note the last assertion — sides 1, 2 and 3 form a flat line rather than a triangle, and <= rather than < is what catches that case.
Common mistakes
- Leaving out the brackets in
(a + b + c) / 2.a + b + c / 2divides onlyc, and every area comes out wrong. - Skipping the triangle check. The function then returns
NaNfor bad input, and the problem shows up somewhere else much later. - Using
<in the check. Sides 1, 2 and 3 pass, and you get an area of 0 for a shape that is really a line.
Try it yourself
- Find the area of an equilateral triangle with all sides 2. You should get about 1.7321.
- Write
perimeter(a, b, c)that uses the same triangle check. - Write
isRightTriangle(a, b, c)that checks whether the square of the longest side equals the sum of the squares of the other two.