0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Calculate Area of Triangle

You can calculate the area of a triangle in JavaScript using the formula area = 0.5 * base * height. For example, const area = 0.5 * base * height; calculates the area when you know the base and height.
📋

Examples

Inputbase = 4, height = 3
OutputArea = 6
Inputbase = 10, height = 5
OutputArea = 25
Inputbase = 0, height = 5
OutputArea = 0
🧠

How to Think About It

To find the area of a triangle, you need to know its base length and height. The area is half the product of these two values. So, multiply the base by the height, then divide by 2 to get the area.
📐

Algorithm

1
Get the base length of the triangle.
2
Get the height of the triangle.
3
Multiply the base by the height.
4
Divide the result by 2 to get the area.
5
Return or print the area.
💻

Code

javascript
const base = 5;
const height = 8;
const area = 0.5 * base * height;
console.log('Area =', area);
Output
Area = 20
🔍

Dry Run

Let's trace the example where base = 5 and height = 8 through the code.

1

Assign base

base = 5

2

Assign height

height = 8

3

Calculate area

area = 0.5 * 5 * 8 = 20

4

Print area

Output: Area = 20

StepVariableValue
1base5
2height8
3area20
4outputArea = 20
💡

Why This Works

Step 1: Use base and height

The formula for the area of a triangle is 0.5 * base * height, so we need these two values.

Step 2: Multiply base and height

Multiplying base by height gives the area of a rectangle covering the triangle.

Step 3: Divide by 2

Since a triangle is half of that rectangle, we multiply by 0.5 to get the triangle's area.

🔄

Alternative Approaches

Using a function
javascript
function triangleArea(base, height) {
  return 0.5 * base * height;
}
console.log('Area =', triangleArea(5, 8));
This makes the code reusable for different base and height values.
Using Heron's formula
javascript
function heronArea(a, b, c) {
  const s = (a + b + c) / 2;
  return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
console.log('Area =', heronArea(3, 4, 5));
This calculates area when you know all three sides, but is more complex.

Complexity: O(1) time, O(1) space

Time Complexity

The calculation uses a fixed number of arithmetic operations, so it runs in constant time.

Space Complexity

Only a few variables are used, so the space needed is constant.

Which Approach is Fastest?

The direct formula is fastest and simplest; Heron's formula is slower due to square root and more inputs.

ApproachTimeSpaceBest For
Direct formula (0.5 * base * height)O(1)O(1)Known base and height
Function wrapperO(1)O(1)Reusable calculations
Heron's formulaO(1)O(1)Known all three sides
💡
Always check that base and height are positive numbers before calculating area.
⚠️
Forgetting to multiply by 0.5 and calculating area as base times height directly.