JavaScript Program to Calculate the Area of a Triangle

To understand this example, you should have the knowledge of the following JavaScript programming topics:


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

area = (base * height) / 2

Example 1: Area When Base and Height is Known

Output

Enter the base of a triangle: 4
Enter the height of a triangle: 6
The area of the triangle 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

Output

Enter side1: 3
Enter side2: 4
Enter side3: 5
The area of the triangle 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.