Languages
[Edit]
EN

JavaScript - calculate triangle area

0 points
Created by:
Iona
445

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}`);

References

  1. Triangle - Wikipedia
  2. Heron's formula - Wikipedia
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join