Signup/Sign In
PUBLISHED ON: DECEMBER 26, 2022

JavaScript Program to Calculate the Area of a Triangle

In geometry, the area of a triangle is calculated by taking half the product of the base and the height of the triangle. In JavaScript, it is possible to write a program that calculates the area of a triangle based on user input. This can be useful for creating applications that require users to input geometric data and perform calculations with that data. In this tutorial, we will learn how to write a JavaScript program that calculates the area of a triangle.

We will also discuss some of the potential challenges and pitfalls that you may encounter when working with geometric calculations in JavaScript. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and know more from here.

To understand this particular example, we need to have a predefined knowledge of some previous topics as :

  • Operators
  • Mathematical function - Math.sqrt()

In order to print the Area of a Triangle we have to consider two cases :

1. Using Base and Height Formula

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

area = (base * height)/2

Code

// Find the Area of the Triangle when we know the base and height 
const base = 8;
const height = 4;

// calculate the Area
const area = (base * height) / 2;

console.log("The area of the triangle is :" , area);


The area of the triangle is : 16

2. Using Herons' Formula

If you know all the sides of the given triangle, you can find the Area using the Herons' Formula. Consider x, y, and z as the three sides of the triangle :

s = (x+y+z)/2
area = Math.sqrt((s(s-x)*(s-y)*(s-z)))

Code

//JavaScript program to find the area of a triangle
const s1 = 3;
const s2 = 4;
const s3 = 5;

//Calculate the semi-perimeter
const s = (s1 + s2 + s3) / 2;

//Calculate the area
const area = Math.sqrt(s * (s - s1) * (s - s2) * (s - s3));

console.log("The area of the triangle is :",area);


The area of the triangle is : 6

Related Topic: JavaScript Interactive Course



About the author:
Proficient in the creation of websites. Expertise in Java script and C#. Discussing the latest developments in these areas and providing tutorials on how to use them.