Member-only story

JavaScript Algorithm: Area of a Triangle

(Beginner) No more complicated math — let code do the heavy lifting!

Max N
2 min readFeb 29, 2024

Calculating the area of shapes gets back to basics from geometry class. But when you just want the triangle area result without the formula every time? We’ve got you covered!

In this quick article, we’ll write a handy JavaScript function to figure out that areas for us by taking in just the base and height as arguments. No pencil or calculator required!

Defining the Function

First, let’s outline the function and parameters:

function triangleArea(base, height) {

}

By defining base and height inside the parentheses, we tell the function to accept those values as inputs.

Calculating the Area

Inside the function body, we simply multiply base * height / 2:

function triangleArea(base, height) {
var area = base * height / 2;

}

This applies the standard geometry formula for any triangle’s area!

Returning the Result

We finish by returning the area value out of the function:

function triangleArea(base, height) {
var area =…

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet