EN
JavaScript - calculate triangle area
0
points
In this article, we would like to show you how to calculate a triangle area using JavaScript.
1. When base and height are given
In this section, we present how to calculate the area of the triangle, when we know its base and height.
|\
| \
h | \ b
|___\
a
Runnable example:
// ONLINE-RUNNER:browser;
const a = 1; // base
const h = 2; // height
const result = (a * h) / 2;
console.log(`The area of the triangle is ${result}`);
2. When all sides are given
In this section, we use Heron's formula to calculate the area of the triangle when all sides are given.
/\
/ \
a / \ b
/ \
/________\
c
Runnable example:
// ONLINE-RUNNER:browser;
const a = 3;
const b = 3;
const c = 1;
const s = (a + b + c) / 2; // semi-perimeter
const result = Math.sqrt(s * (s - a) * (s - b) * (s - c));
console.log(`The area of the triangle is ${result}`);