JavaScript Program to Calculate the Area of a Triangle

In this example, you'll learn to write a program to calculate the area of a triangle in JavaScript.

If you know the base and height of a triangle, we can find the area using the formula:

area = base of triangle * height of triangle / 2

Example 1: Area When Base and Height is Known

let baseValue = prompt('Enter the base of a triangle: ');
let heightValue = prompt('Enter the height of a triangle: ');

// calculate the area
let areaValue = (baseValue * heightValue) / 2;

console.log(
  `The area of a triangle with base ${baseValue} and height ${heightValue} is ${areaValue}`
);

Output

Enter the base of a triangle: 4
Enter the height of a triangle: 6
The area of a triangle with 4 base and 6 height is 12

If you know all the sides of a triangle, you can find the area using Herons' formula. If a, b and c are the three sides of a triangle, then

s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))

Example 2: Area When All Sides are Known

// JavaScript program to find the area of a triangle

let side1 = prompt('Enter side1: ');
let side2 = prompt('Enter side2: ');
let side3 = prompt('Enter side3: ');

// calculate the semi-perimeter
let s = (side1 + side2 + side3) / 2;

//calculate the area
let areaValue = Math.sqrt(
  s * (s - side1) * (s - side2) * (s - side3)
);

console.log(
  `The area of a triangle with side length ${side1}, ${side2}  and ${side3} is ${areaValue}`
);

Output

Enter side1: 3
Enter side2: 4
Enter side3: 5
The area of a triangle with side length 3, 4  and 5 is 6

Here, we have used the Math.sqrt() method to find the square root of a number.

Note: If a triangle cannot be formed from the given sides, the program will not run correctly.